嵌套表单和构建关联

发布于 2024-10-08 10:05:25 字数 662 浏览 0 评论 0原文

我正在制作添加到购物车的表单。看起来像这样

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜心小果奶 2024-10-15 10:05:25

我需要更多信息来确定,但似乎 LineItem belongs_to :product 和 Product 不应该 belong_to :line_item 除非那里确实存在 1-1 关系(这对我来说没有意义,并且不遵循此类系统的正常约定)

注意**在 form_forfields_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 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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文