fields_for ブロック内で、関係フィールドの値を参照するにはどうすればよいですか。
例えば:
アプリ/モデル/cart.rb
class Cart < ActiveRecord::Base
attr_accessible :lineitems_attributes
has_many :lineitems, dependent: :destroy
accepts_nested_attributes_for :lineitems
def total_price
lineitems.to_a.sum { |item| item.total_price }
end
end
アプリ/モデル/ラインアイテム.rb
class Lineitem < ActiveRecord::Base
attr_accessible :cart_id, :quantity, :package_id, :part_id
belongs_to :cart
belongs_to :package
belongs_to :part
def total_price
if package_id?
return package.price * quantity
end
if part_id?
return part.price * quantity
end
end
end
アプリ/モデル/package.rb
class Package < ActiveRecord::Base
attr_accessible :description, :img_src, :name, :price
has_many :lineitems
end
アプリ/ビュー/カート/_form.html.erb
<%= form_for @cart do |f| %>
<%= c.fields_for :lineitems do |i| %>
<%= render 'lineitem_fields', :f => i %>
<% end %>
<%= c.submit %>
<% end %>
アプリ/ビュー/カート/_lineitem_fields.html.erb
<%= f.text_field :quantity %>
<% if :package_id? %>
<%= f.text_field :package_id %>
<% else %>
<%= f.text_field :part_id %>
<% end %>
<%= link_to 'Remove',
lineitem_path(:id),
:method => :delete,
:confirm => t('.confirm', :default => t("helpers.links.confirm",
:default => 'Are you sure?')) %>
スキーマの相対的部分
create_table "carts", :force => true do |t|
t.integer "branch_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "lineitems", :force => true do |t|
t.integer "cart_id"
t.integer "part_id"
t.integer "package_id"
t.integer "quantity", :default => 1
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "parts", :force => true do |t|
t.string "description"
t.string "partNumber"
t.decimal "price"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "packages", :force => true do |t|
t.string "description"
t.string "name"
t.string "img_src"
t.decimal "price"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
上記のフォームは機能しますが...
質問 1: :package_id の代わりに package.name を表示する方法
質問 2: フォーム内の各項目の total_price を表示する方法。それはどのように機能するのですか?
質問 3: フォームを請求書のように表示するベスト プラクティスはありますか? 数量はテキスト フィールドで、残りの列はテキストまたはラベルである可能性があります。
最終的なシナリオは、このフォームが、注文を送信する前にカートの数量を編集する (または項目を削除する) 最後のチャンスになることです。明らかに現実の世界では、数量、パッケージ名、説明、価格を表示したいのですが、これらの値は関係によって別のモデルにあり、ラインアイテムに固有ではないため、フォーム内にこれらの値を表示する方法がわかりません。
助けてくれてありがとう。