Nested Forms and Building associations
I'm working on a add to cart form. It looks something like this
#Models
Order.rb
has_many :line_items
accepts_nested_attributes_for :line_items, :allow_destroy => true
LineItem.rb
has_one :product
belongs_to :order
Product.rb
belongs_to :line_item
I'd like to create a form in product#show to allow multiple related products to be added to the order/cart at once, basically create or update a line item for each product.
Probably something like this in the view (HAML to keep it brief).
-form_for @order do |f|
- if has_related?
- for related in @products.related_products
- f.field_for :line_item do |li_form|
= li_form.text_field :quantity
= li_form.hidden_field :product_id
= related.product_name
What would it take开发者_运维知识库 to actually make something like this work?
I would need more info to be sure, but it seems that a LineItem belongs_to :product
and Product should NOT belong_to :line_item
unless there really is a 1-1 relationship there (which wouldn't make sense to me, and doesn't follow the normal convention of these sorts of systems)
Note** using -
before form_for
and fields_for
has been deprecated in rails 3 in favor of =
since the form does actually render html
= fields_for :line_items do |li_form|
is the syntax for a has_many relationship
The rest all depends on your user experience design.
Hope this helps!
精彩评论