Given that I have the next models:
user.rb
has_many :favorites, dependent: :destroy
has_many :sports, through: :favorites
sport.rb
has_many :favorites, dependent: :destroy
has_many :users, through: :favorites
In the form for create a new user, there is a list of checkboxes of sports, and in the user validation I want to validate that at least one is selected.
I'm doing it like this:
In the user controller create action:
@user = User.new(params[:user])
@user.sports << Sport.find(params[:sports]) unless params[:sports].nil?
if @user.save ...
In the user model
validate :user_must_select_sport
def user_must_select_sport
if sports.empty?
errors.add(:Sport, "You have to select at least 1 sport")
end
end
And it's actually working, but I'm guessing that it has to be a better way of doing this. I'd appreciate any help.
This helper validates the attributes' values by testing whether they match a given regular expression, which is specified using the :with option. Alternatively, you can require that the specified attribute does not match the regular expression by using the :without option. The default error message is "is invalid".
In Rails, validations are used in order to ensure valid data is passed into the database. Validations can be used, for example, to make sure a user inputs their name into a name field or a username is unique.
If any validations fail, the object will be marked as invalid and Active Record will not perform the INSERT or UPDATE operation. This helps to avoid storing an invalid object in the database. You can choose to have specific validations run when an object is created, saved, or updated.
You can use "validates_presence_of"
class User < ActiveRecord::Base
has_many :sports
validates_presence_of :sports
end
But there is a bug with it if you will use accepts_nested_attributes_for
with :allow_destroy => true
.
You can look into this : Nested models and parent validation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With