嵌套表单和构建关联
我正在制作添加到购物车的表单。看起来像这样
#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
我想在product#show中创建一个表单,以允许一次将多个相关产品添加到订单/购物车中,基本上为每个产品创建或更新一个订单项 。
视图中可能是这样的(HAML 保持简短)。
-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
真正让这样的事情发挥作用需要什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我需要更多信息来确定,但似乎 LineItem
belongs_to :product
和 Product 不应该belong_to :line_item
除非那里确实存在 1-1 关系(这对我来说没有意义,并且不遵循此类系统的正常约定)注意**在
form_for
和fields_for< 之前使用
-
/code> 在 rails 3 中已被弃用,取而代之的是=
,因为表单实际上渲染了 html= fields_for :line_items do | li_form|
是 has_many 关系的语法其余的一切都取决于您的用户体验设计。
希望这有帮助!
I would need more info to be sure, but it seems that a LineItem
belongs_to :product
and Product should NOTbelong_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
-
beforeform_for
andfields_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 relationshipThe rest all depends on your user experience design.
Hope this helps!