Rails - 使用fields_for创建动态数量的新记录

时间:2013-11-21 18:14:46

标签: ruby-on-rails nested-attributes model-associations fields-for

我正在使用fields_for表单为x个相关项目创建选择输入表单。在这种情况下,它是与条目相关联的游戏。我想让用户为条目中的每个游戏选择一个胜利者并存储他们的选择。这是我的表格。

<%= simple_form_for [@contest, @entry] do |f| %>

...某些领域,然后......

<div class="form-group">
<%= f.label :games %><br>
<% Contest.find_by_id(params[:contest_id]) do |contest| %>
<%= f.simple_fields_for :entry_selections do |selection| %>    
  <table>
    <table class="table table-half">
      <thead>
        <tr>
          <th>Away</th>
          <th>Home</th>
          <th>Choose Winner</th>    
        </tr>
      </thead>
        <tbody>
        <% contest.matchset.games.each do |game| %>
          <tr>
            <td><%= game.away_team_name %></td> 
            <td><%= game.home_team_name %></td>
            <td><%= selection.input :team_selected, collection: [[game.away_team_id, game.away_team_name], [game.home_team_id, game.home_team_name]], :label_method => :last, :value_method => :first, :required => false, label: false %></td>
          </tr>
        <% end %>
        <% end %> 
      </tbody>
      </table>
  <% end %>
</div>

我正在尝试将每个:team_selected保存在名为entry_selections的模型上。我认为原因是因为它不能出于某种原因在那里创建一个新的记录。这是来自服务器日志。

Processing by EntriesController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"HniBF1MQyBdgcNT71vAfyGr4BuJ+OlPBENmVo7FN6hc=", "entry"=>{"name"=>"", "user_id"=>"1", "contest_id"=>"22", "entry_selections"=>{"team_selected"=>"1"}}, "commit"=>"Update Entry", "id"=>"12"}
  Entry Load (0.2ms)  SELECT "entries".* FROM "entries" WHERE "entries"."id" = ? LIMIT 1  [["id", "12"]]
Unpermitted parameters: entry_selections

我还将其添加到entries_controller。

def entry_params
  params.require(:entry).permit(:name, :user_id, :contest_id, :matchset_id, entry_selections_attributes: [:game_id, :team_selected, :game_weight])
end

My Entries模型has_many:entry_selections和我的EntrySelections模型belongs_to:entry

有没有人对如何存储每个游戏的用户团队选择有任何建议?

编辑:添加比赛模型和entry_selections模型

contest.rb

class Contest < ActiveRecord::Base
has_many :entries

...

validates :league_name, :league_id, :matchset_id, :size, presence: true
end

entry_selection.rb

class EntrySelection < ActiveRecord::Base
belongs_to :entry

validates :team_selected, presence: true

end

1 个答案:

答案 0 :(得分:0)

我还是铁杆新手,但这应该是正确的:

  

entry_selections_attributes:

应该是

  

entry_selections