Welcome to Working With Rails

 

Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
Validation & error display with has_many :through
2 Posts
Validation & error display with has_many :through

I have a form that is used to feed a has_many :through association that I need to validate. I've named all the fields so that they make sense, but I'm not sure how to validate against required fields.

I have validates_presence_of on the foreign_key ids in the join model, as well as a check in the code that makes sure the foreign keys exist. One of the two is at least stopping the form from submitting, but no errors are displayed.

So my question is where do the validation checks need to be and how should they be written so that I can do error_messages_for?

My model setup can be viewed at http://www.workingwithrails.com/forums/4/topics/724-help-with-has-many-through-and-intermediate-attributes

you could use "validates_associated":http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M002114, to have the intermediate or destination model validations run.

say you have contractors, which have a many to many relationship with customers thru the Contract model, and you want the Contract validations to be run when saving a Contractor:

class Contractor

   has_many :contracts
   has_many :customers, :through => :contracts
   validates_associated :contracts
end

 class Contract
     belongs_to :company
     belongs_to :customer
     validates_presence_of :company_id
     validates_presence_of :customer_id
  end

  class Customer
     has_many :contracts
     has_many :companies, :through => contracts
  end

as the api says, be careful not to have circular references, or you'll run into infinite loops.

2 Posts
Login to add your message