の線に沿って何かをしようとしていました。そして、あなたは:accepts_nested_attributes_for
を使ってフォームでそれを扱うことができます。例を与えることを
が、ここで私はモデルを構築する方法を次のとおりです。
class List < ApplicationRecord
has_many :list_items, inverse_of: :list
has_many :items, through: :list_items
# This allows ListItems to be created at the same time as the List,
# but will only create it if the :item_id attribute is present
accepts_nested_attributes_for :list_items, reject_if: proc { |attr| attr[:item_id].blank? }
end
class Item < ApplicationRecord
has_many :list_items
has_many :lists, through: :list_items
end
class ListItem < ApplicationRecord
belongs_to :list, inverse_of: :list_items
belongs_to :item
end
そのモデル構造のある場所で、ここに新しいリストを作成するための図の一例です。
<h1>New List</h1>
<%= form_for @list do |f| %>
<% @items.each_with_index do |item, i| %>
<%= f.fields_for :list_items, ListItem.new, child_index: i do |list_item_form| %>
<p>
<%= list_item_form.check_box :item_id, {}, item.id, "" %> <%= item.name %>
</p>
<% end %>
<% end %>
<p>
<%= f.submit 'Create List' %>
</p>
<% end %>
ここで何が起こっているのかを説明するために、@items
がリストに追加することができ、すべてのアイテムを持っているためにプリロード変数です。私は各Itemをループし、手作業でFormBuilderメソッドfields_for
に渡します。
手動で行うので、:child_index
を同時に指定する必要があります。そうしないと、それぞれのチェックボックスに前の項目と同じ名前属性(つまりname="list[list_item_attributes][0][item_id]"
)が追加され、サーバ。
そして、次のように宣言していcheck_box
FormBuilder方法:
def check_box(method, options = {}, checked_value = "1", unchecked_value = "0")
チェックボックスをオンにしたとき、それはitem.id
から値を持っており、それならばそのようしたがって、上記の形で、私はそれらのデフォルト値を置き換えますチェックされていない場合、値は空白です。これをリストモデルのという宣言と組み合わせてください。ここでは:item_id
が空白の場合に拒否する必要があり、チェックされた項目に対してのみListItemを作成した結果が得られます。
この作品を作るための最後のものは、このように、コントローラ内でネストされた属性を可能にすることである。
def allowed_params
params.require(:list).permit(list_items_attributes: [:item_id])
end
あなたのコードは現在どのように見えますか? – raidfive
あなたの質問にいくつかのコードを追加してください。正確に何を試しましたか –
確信しているコード – Kevin