views:

86

answers:

1

I have built a custom form for creating a joining model on a has_many :through relationship. The models look roughly like this:

class Team
  has_many :team_members
  has_many :members, :through => :team_members
end

class Member
  has_many :team_members
  has_many :teams, :through => :team_members
end

class TeamMember
  belongs_to :team
  belongs_to :member
  # and this model has some validations too
end

The form I have built is for selecting which members should be in a team. I won't paste the form, but it uses the form_tag method and basically sends an array of hashes which contain a member_id and a squad_number. I then update the database with an action that looks roughly like this (simplified a bit, but you get the jist):

@team.transaction do
  @team.team_members = params[:team_members].collect{|tm| @team.team_members.new(tm)}
  if @team.save
    redirect_to ...
  else
    render :action => :members
  end
end

Everything works great but I am validating the squad_number for uniqueness and numerically. So, when any of those validations fail, how do I get access to them in my view, and how do I ascertain which of the many members it has failed on?

A: 

I'm not sure this will give you what you want, but you can create your team_members just like this

team_members = @team.team_members.create(params[:team_members])

and have access to the errors through team_members.errors.

j.
Thanks for your answer. Although this action is also used for editing and removing team members (ie, if `params[:team_members]` doesn't contain the ID of an existing team member then it needs to be removed) hence my slightly uglier code ;)
aaronrussell