4

フォームを投稿すると、次のエラーが表示されます: ID のないチームが見つかりませんでした

以下の投稿パラメーターがあります

{"utf8"=>"✓",
 "_method"=>"put",
 "authenticity_token"=>"knq4dG1U/5NJxMD6KYxfOpKd3CuOBHRlp6xCwdpwCnQ=",
 "match"=>{"name"=>"latest match",
 "date(1i)"=>"2013",
 "date(2i)"=>"5",
 "date(3i)"=>"19",
 "teams_attributes"=>{"1368967240149"=>{"name"=>"Navi",
 "id"=>"1"}}},
 "commit"=>"Update Match",
 "match_id"=>"2"}

モデル:

team has_many :matchips

team has_many :matches :through => matchips

match has_many :matchips
match has_many :teams :through => matchips

チーム コントローラー:

  def create


    @team = Team.find(params[:team_id])  <-----fails here!


    redirect_to @match

  end

形:

<%= nested_form_for @match, :url => {:action => "add_team_to_match_post"} 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 %>

だから私は基本的に試合とチームの間に多対多の関係を持っています。一致にnested_formを使用していますが、問題は、作成または更新する前に関連付けを探していることです. 私は以前、親が作成または更新されたときに子モデルが作成される多対1の関連付けでこれを行いました.だから私はそれをその試合に関連付けることができます。

既に作成されたエンティティを関連付けるより良い方法がある場合は、お知らせください。

4

4 に答える 4

2

おそらく次のようなものが必要です。

def add_team_to_match_post

    @match = Match.find(params[:match_id])

    params[:teams_attributes].each_value do |team_attributes|
      team = Team.find(team_attributes[:id])
      @match.teams << team
      team.matches << @match
    end

    redirect_to @match
end

基本的に、これはteams_attributesハッシュ内のすべてのチームを繰り返し処理し、それを一致オブジェクトに追加します (これは多対多であるため)

于 2013-05-19T15:44:29.890 に答える
0

has_manyfor Matches <> Teams はやり過ぎです。has_two 関係のモックについては、このソリューションを参照してください。これにより、フォームと URL が大幅に簡素化されます。

于 2013-05-24T04:34:48.470 に答える