[英]Rails collection_select form adds selected value to an array
我有一個Rails 4應用程序,它是一個游戲數據庫。 與該問題相關的模型是:
它具有游戲/新表格,可創建新的游戲記錄。
在該表單中,我需要一個子表單,允許用戶添加類型。 我設想它的工作方式如下:
Genre.all
填充的 add_genre
保存”時,該應用程序會使用我定義的add_genre
函數為每種流派創建GameGenre
關系記錄。 這是我目前的games/new.html.erb
查看代碼:
<div id="game-genres-form">
<%= fields_for(@game.game_genres.build) do |f| %>
<div><%= hidden_field_tag :game_id, @game.id %></div>
<div class="form-group">
<%= f.label :genre_id, "Add a genre" %>
<div class="input-group">
<%= f.collection_select :genre_id, Genre.all, :id, :name,
{}, {:class=>'form-control'} %>
<span class="input-group-btn">
<%= f.submit "Add", class: "btn btn-default" %>
</span>
</div>
<% end %>
</div>
這不起作用,因為fields_for(@game.game_genres.build)
不正確。 實際上,目前,當我單擊“添加”時,它會提交新游戲表格並創建游戲記錄,但不會添加流派。
我想我需要知道的是,我用什么代替fields_for(@game.game_genres.build)
將提交的類型傳遞給新數組? 以及如何在games_controller.rb
?
我意識到<div><%= hidden_field_tag :game_id, @game.id %></div>
是不必要的(因為在保存新游戲記錄之前game_id
不存在)。
我希望我有道理,謝謝您的幫助。
這些是我當前的關聯,它們缺少accepts_nested_attributes_for
。 目前,我還不太擔心-我主要想知道要使用的正確類型的表單,以及如何使每種類型都添加到哈希/數組中。
class Game < ActiveRecord::Base
belongs_to :user
has_many :game_genres, foreign_key: :game_id,
dependent: :destroy
has_many :genres, through: :game_genres
class GameGenre < ActiveRecord::Base
belongs_to :game
belongs_to :genre
class Genre < ActiveRecord::Base
belongs_to :user
has_many :game_genres, foreign_key: :genre_id,
dependent: :destroy
has_many :games, through: :game_genres
可能是您的游戲模型中缺少這樣的東西
accepts_nested_attributes_for :game_genres ,allow_destroy: true
或者您可以嘗試在您的視圖中保存流派
<%= collection_select(:category, :ids, Category.all, :id, :category, { :selected => @categories.map{|m| m.id}}, {:multiple=>true}) %>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.