Note that there are some explanatory texts on larger screens.

plurals
  1. PORails Validate child with parent
    text
    copied!<p>I have a nested Form</p> <p>A Crew can have many meetings, a Meeting can belong to one Crew. A Crew, and a Meeting can both have set a gender_id attribute.</p> <p>I want to add an error to the Meeting object when Crew.meeting_id != Meeting.gender_id</p> <p>I have written a simple validator</p> <pre><code>class MeetingGenderValidator &lt; ActiveModel::EachValidator def validate_each(record, attribute, value) if record.gender_id != record.crew.gender_id msg = :wrong_gender case record.crew.gender_id when 1 then msg = :crew_woman_only when 2 then msg = :crew_man_only record.errors.add(attribute, msg, options) end end end end </code></pre> <p>The problem is, When this validator is run, The record variable (our Meeting model), is not yet associated with the Crew model, so I get an error on calling Nil.gender_id</p> <p>Here is the part of Meeting model:</p> <pre><code>class Meeting &lt; ActiveRecord::Base belongs_to :crew validates :gender_id, :meeting_gender =&gt; true end </code></pre> <p>Here is the part of Crew model with the association:</p> <pre><code>class Crew &lt; ActiveRecord::Base has_many :meetings accepts_nested_attributes_for :meetings end </code></pre> <p>And my Crews#Create action snippet (controller):</p> <pre><code>class CrewsController &lt; ApplicationController def create @crew = Crew.new(params[:crew]) # here are the meeting params too @crew.user = current_user # assigning the user from session / not important here if @crew.save ...... end end </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload