Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation on a has_many relationship in rails 3.2

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.

like image 670
Daniel Romero Avatar asked Jan 27 '13 13:01

Daniel Romero


People also ask

How do I validate in Ruby on Rails?

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".

What is validate in rails?

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.

Can we save an object in DB if its validations do not pass?

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.


1 Answers

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

like image 143
Ramandeep Singh Avatar answered Oct 28 '22 03:10

Ramandeep Singh