Skip to content

Instantly share code, notes, and snippets.

@theinventor
Created November 28, 2012 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theinventor/4163417 to your computer and use it in GitHub Desktop.
Save theinventor/4163417 to your computer and use it in GitHub Desktop.
simple_form_stuff
####TO CREATE A BOOLEAN VIRTUAL ATTRIBUTE WITH VALIDATION:
##In the model:
class Person < ActiveRecord::Base
validates_acceptance_of :terms_of_service
#if using attr_accessible
attr_accessible :name, :etc, :terms_of_service
end
##In the view:
= f.input :terms_of_service, as: :boolean, required: true
####TO CREATE A (non-boolean) VIRTUAL ATTRIBUTE WITH VALIDATION IN SIMPLE_FORM:
##In the model:
class Person < ActiveRecord::Base
attr_accessor :nickname
validates_presence_of :email, :first_name, :nickname
#if using attr_accessible
attr_accessible :name, :etc, :nickname
end
##In the view:
= f.input :nickname
####TO VALIDATE A SIMPLE ASSOCIATION IN SIMPLE_FORM:
##In the model:
class LineItem < ActiveRecord::Base
belongs_to :order
validates_presence_of :order_id
end
####TO VALIDATE A CUSTOM THING IN SIMPLE_FORM:
##In the model:
class Person < ActiveRecord::Base
validates :name_cannot_be_fake
def name_cannot_be_fake
errors.add(:first_name, "can't be so fake") if self.first_name.downcase.include?("fake")
end
end
####TO VALIDATE A HAS AND BELONGS TO MANY IN SIMPLE_FORM:
##In the model:
class Person < ActiveRecord::Base
has_and_belongs_to_many :roles
validate :must_have_a_role
def must_have_a_role
errors.add(:roles, "We need at least 1 role") if self.roles.size == 0
end
end
##In the view:
= f.association :roles
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment