こんにちは、同志です!
私が達成しようとしているのは、注文フォームが次の 2 つの方法でコンパイルされるシステムです。
- 独自の属性 (:sender_name、:sender_mobile など) を埋めることによって
- 製品に貼られた価格ラベルで製品を選択します。
あれこれいじっていると、なんとかオーダーフォームに商品一覧が表示されました。ここに 3 つのモデルとビュー
models/order.rb
class Order < ActiveRecord::Base
attr_accessible :sender_comment, :sender_email, :sender_mobile, :sender_name, :order_attributes
has_many :products
accepts_nested_attributes_for :products
end
models/product.rb
class Product < ActiveRecord::Base
belongs_to :order
attr_accessible :product_name, :product_description, :prices_attributes, :order_id
has_many :prices
accepts_nested_attributes_for :prices
end
モデル/価格.rb
class Price < ActiveRecord::Base
belongs_to :product
attr_accessible :product_id, :price_label, :price_amount, :price_checked, :how_many_prices, :products_attributes
end
ビュー/注文/_form.html.erb
<%= form_for(@order) do |f| %>
<div class="field">
<%= f.label :sender_name %><br />
<%= f.text_field :sender_name %>
</div>
# [...] other order's fields...
<%= f.fields_for :product do |builder| %>
<%= render "products_field", :f => builder %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
ビュー/注文/_products.html.erb
<% @products.each do |p| %>
<td><%= p.product_name %></td>
<td><%= p.product_description %></td><br />
<% p.prices.each do |price| %>
<td><%= price.price_label %></td><br />
<td><%= price.price_amount %></td><br />
<td><input type="radio" class="order_bool" name="<%= p.product_name %>" <% if price.price_checked == true; puts "SELECTED"; end %> value="<%= price.price_amount%>"/></td><br />
<% end %>
<% end %>
製品と相対価格は注文フォームに出力されますが、一度選択すると order_attributes として保存されません。注文の属性とともに、選択されたすべてのラジオはこのようなオブジェクトを生成します
[#<Product id: nil, order_id: 23, product_name: nil, product_description: nil, created_at: nil, updated_at: nil>]
選択した製品を有効な order_attributes に変換するにはどうすればよいですか?
これは OOP を使用した最初のプロジェクトであり、インターネットからの助けを借りて、すべてを独力で学んでいます。あまり厳しくしないでください!
また、タイトルが適切でないと思われる場合は、自由に変更してください。英語は私の母国語ではないので、この問題を一言で要約するのは非常に難しいと思います.
患者をありがとう:)