尝试做多对多的关系。
我有两个模型,团队和匹配,我正在进行多对多关系,但在尝试保存嵌套模型时遇到此错误。
'无法找到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 %>
控制器