Wrap multiple validations in a context - ruby-on-rails

With validation context we can do:
validates :title, presence: true, on: :published
validates :content, length: { maximum: 50 }, on: :published
Is it possible to wrap multiple validations that share a context something like the following?
on: :published do
validates :title, presence: true
validates :content, length: { maximum: 50 }
end

Yes, you can group validations using the with_options method:
with_options(on: :published) do |record|
record.validates :title, presence: true
record.validates :content, length: { maximum: 50 }
end
See the Rails Guides, this article and the sources for more info.

Related

How to structure a Ruby on Rails model?

In our app's User model, we already have:
attr_accessor :remember_token, :activation_token, :reset_token
before_save :downcase_email
before_create :create_activation_digest
before_save { self.email = email.downcase }
validates :first_name, presence: true, length: { maximum: 50 }
validates :last_name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, presence: true, length: { minimum: 6 }, allow_nil: true
Now, we need to add relationship associations to the model, namely:
has_many :roles, dependent: :destroy
has_many :agendas, through: :roles
Does it matter whether we include the latter go BEFORE or AFTER the former, in the model?
If so, what is the recommended / preferred / best way?
It doesn't matter, but the important thing is to be consistent. A usual best practice is to first do all you can to declare the class' structure, before you get in to any operational details. For example:
class User < ActiveRecord::Base
attr_accessor :remember_token, :activation_token, :reset_token
has_many :roles, dependent: :destroy
has_many :agendas, through: :roles
before_save :downcase_email
before_create :create_activation_digest
before_save { self.email = email.downcase }
validates :first_name, presence: true, length: { maximum: 50 }
validates :last_name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, presence: true, length: { minimum: 6 }, allow_nil: true
end
Again, this is just one way to do things, but it's very common amongst Rails applications.

Ruby: How can i make a combobox that shows

i want to know how to make a commbobox that shows a list of all users in my database, let me explain myself:
I have two clases:
class User < ActiveRecord::Base
validates :password, presence: true, confirmation: {strict: true}
validates :password_confirmation, presence: true
validates :telephone, uniqueness: true, presence: true, numericality: { only_integer: true }, presence: true, length: { minimum: 9, maximum: 9 }
validates :name, presence: true, length: { minimum: 4, maximum: 30 }, format: { with: /^[\w\s-]*/u, multiline: true,
message: 'only allows letters' }
has_many :valorations
end
class Valoration < ActiveRecord::Base
validates :points, presence:true, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 100 }
belongs_to :user
belongs_to :hability
end
And i have a show create view for the validation class:
<%= form_for(#valoration) do |f| %>
...errors check...
<div class="field">
#combo box code to be added
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
And what i wanna do is to create a combo box that does something like the following pseudocode using fselect:
Invented code:
<%= f.select :user_id, options_for_select( for_each user do |u|
[[u.name,u.id]]
end %>
So at the end i have an combobox with all the users, i'm a noob to rails really know how to do it so any help is welcome
You can do something like below to achieve what you want.
<%= f.select :user_id, User.all.collect { |u| [ u.name, u.id ] } %>
For more info, you can refer to this link

Rails 4 active record validation - Conditionally validate interdependent presence of 4 attributes

I have a form with 10 attributes.
Among them I have 4 attributes which I need to apply what I'd call a"mutually conditional presence" Active Record validation.
these attributes are
address_line_1
zipcode
state
country
It means that if the user fills ONE of them then ALL the others have to be present
So far I have only be able to say that if the user fills the first attribute "address line 1" then all the others must be present.
But it does not validate that all the MUTUAL presences in all possible combinations. For example if the user lets 'address line 1' empty but fills zipcode and leaves the other three empty, I want active recoird not to validate the form as he then should have been asked to fill the other three attributes. And so on with each of the attibutes.
How to do this?
Here is my current code
spec/models/users
validates :address_line_1,
presence: true,
length: { maximum: 100,
minimum: 3 }
validates :zipcode,
presence: true, if: :address_line_1?,
length: { maximum: 20,
minimum: 4}
validates :state,
presence: true, if: :address_line_1?,
validates :country,
presence: true, :address_line_1?,
length: { maximum: 50}
Just replace :address_line?condition with a check for one of the filled out fields:
validates :address_line_1,
presence: true, if: :address_entered?,
length: { maximum: 100,
minimum: 3 }
validates :zipcode,
presence: true, if: :address_entered?,
length: { maximum: 20,
minimum: 4
validates :state,
presence: true, if: :address_entered?,
validates :country,
presence: true, if: :address_entered?,
length: { maximum: 50}
def address_entered?
address_line_1.present? || zipcode.present? || state.present? || country.present?
end

Rails validate statement checking for blank content

I have the following code in models/micropost.rb
class Micropost < ActiveRecord::Base
belongs_to :user
validates :content, length: { maximum: 140}
validates :content, length: { minimum: 1 }
The first validation line is fine. However, in the second line I am trying to check for blank in content and something is going wrong? I think there's a problem with the multiple validates statements maybe? I'm pretty new to rails... :(
You can simply validate presence:
validates :content, length: { maximum: 140 }, presence: true
You can validate min and max length by using in range
validates :content, length: { in: 1..140 }

how to skip model validation for particular function in rails?

I want to skip some model validation for controller functions. I am doing like this
Model :
attr_accessible :skip_method_2
validates :name, presence: true, length: { maximum: 50 }, :unless => :skip_method_2
VALID_PHONE_REGEX = /\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/
validates :phoneno, presence: true,uniqueness: { case_sensitive: false, :scope => :user_id}, format: { with: VALID_PHONE_REGEX }, :unless => :skip_method_2
Controller :
def contacts_callback
#contacts = request.env['omnicontacts.contacts']
#contacts.each do |contact|
next if current_user.contacts.exists?(:email => "#{contact[:email]}")
contact1 = current_user.contacts.new(:skip_method_2 => true)
contact1.name = contact[:name]
contact1.email = contact[:email]
contact1.group = "Others"
contact1.save
end
redirect_to "/contact"
end
I dont want to save it by :validation => false. I want to skip name and phoneno validation for contacts_callback function. But it is not working.
It gives error in controller -
undefined local variable or method `skip_method_2' for contacts_callback. I already mentioned attr_accessible in my model
Change validates :name, presence: true, length: { maximum: 50 }, :unless => :skip_method_2
to
validates :name, presence: true, length: { maximum: 50 }, :unless => lambda {|x| x.skip_method_2}
Also checkout this answer

Resources