Reputation: 1598
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.
Upvotes: 7
Views: 5975
Reputation: 5253
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
Upvotes: 8