7

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.

tereško
  • 58,060
  • 25
  • 98
  • 150
Daniel Romero
  • 1,581
  • 1
  • 20
  • 33

1 Answers1

8

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

Community
  • 1
  • 1
Ramandeep Singh
  • 5,063
  • 3
  • 28
  • 34