I have a nested Form
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.
I want to add an error to the Meeting object when Crew.meeting_id != Meeting.gender_id
I have written a simple validator
class MeetingGenderValidator < 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
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
Here is the part of Meeting model:
class Meeting < ActiveRecord::Base
belongs_to :crew
validates :gender_id, :meeting_gender => true
end
Here is the part of Crew model with the association:
class Crew < ActiveRecord::Base
has_many :meetings
accepts_nested_attributes_for :meetings
end
And my Crews#Create action snippet (controller):
class CrewsController < 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
Have found a workaround, in the Crews controller:
I now, it’s not pretty, but it works, it can be delegated to a model method, but I want show here a working solution. The question is still open…