试图做多对多的关系。
我有两个模型,Teams 和 Matches,我正在做一个多对多的关系,但在尝试保存嵌套模型时出现此错误。
'找不到 ID=2 的团队以匹配 ID='
我知道我的模型是新的,所以它还没有 id,但我正在使用 Match.new(params[:match] 应该可以工作的方法。
Team:
class Team < ActiveRecord::Base
attr_accessible :description, :name, :status
attr_protected :id
has_many :matchships
has_many :matches, :through => :matchships
end
Match:
class Match < ActiveRecord::Base
attr_accessible :date, :name
attr_protected :id
has_many :matchships
has_many :teams , :through => :matchships
accepts_nested_attributes_for :teams
end
MatchShips:
class Matchship < ActiveRecord::Base
attr_accessible :match_id, :team_id
belongs_to :match
belongs_to :team
end
Match Controller:
New:
def new
@match = Match.new
@match.teams.build
end
Create:
def create
'failing here' --------> @match = Match.new(params[:match])
@team = Team.find(params[:team_id])
@match.teams << @team
@team.matches << @match
形式:
<%= nested_form_for(@match) do |f| %>
<% if @match.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@match.errors.count, "error") %> prohibited this match from being saved:</h2>
<ul>
<% @match.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :date %><br />
<%= f.date_select :date %>
</div>
<%= f.fields_for :teams, :html => { :class => 'form-vertical' } do |builder| %>
<%= builder.label "Team Name:" %>
<%= builder.autocomplete_field :name, autocomplete_team_name_teams_path, :update_elements => {:id => "##{form_tag_id(builder.object_name, :id)}" },:class => "input-small",:placeholder => "Search" %>
<%= builder.hidden_field :id %>
<% end %>
<%= f.link_to_add raw('<i class="icon-plus-sign"></i>'), :teams, :class => 'btn btn-small btn-primary' %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
控制器