【问题标题】:HABTM with extra attributes on nested formHABTM 在嵌套表单上具有额外属性
【发布时间】:2013-07-17 17:27:18
【问题描述】:

我的产品拥有并属于许多 product_links

class Product < ActiveRecord::Base

has_many :map_product_prices
has_many :product_links, :through => :map_product_prices
accepts_nested_attributes_for :product_links

还有……

class ProductLink < ActiveRecord::Base

has_many :map_product_prices
has_many :products, :through => :map_product_prices
accepts_nested_attributes_for :products

我为此使用 Ryan Bates 'nested_form' gem。这是我无法解决的问题。地图还附有价格属性。

class MapProductPrice < ActiveRecord::Base

attr_accessible :product_link_id, :product_id, :price

belongs_to :product
belongs_to :product_link

我有一个多选框,可以在产品链接表单上选择一个或多个产品。但那是当我切换到 Ryans gem 以使用嵌套表单时,我可以有一个选择框来选择产品,然后是一个文本字段来输入价格。然后我可以根据需要添加/删除它们。

这是我的看法:

    <%= f.fields_for :products do |product| %>
        <%= product.select :product_id, options_for_select(select_options) %>
        <%= product.text_field :price %>
        <%= product.link_to_remove "Remove this product" %>
    <% end %>
    <p><%= f.link_to_add "Add a product", :products %></p>

有人对如何最好地完成此任务有任何想法吗?

我从这个表单中得到的是产品没有 product_id 属性。这是有道理的,因为 product_id 在映射表上,而不是在产品上。那么我如何才能以这种嵌套形式而不是产品来引用映射表呢?我不希望能够添加新产品,我希望能够通过在每个映射旁边添加价格来向现有产品添加新映射。

谢谢

编辑: 我已经编辑了我的代码以反映我尝试过的很多。当我查看视图时,它告诉我产品构建器对象上没有 product_id 或 price 属性。如何将此设计转换为表单并使其工作?谢谢

【问题讨论】:

    标签: ruby-on-rails nested-forms has-and-belongs-to-many


    【解决方案1】:

    您需要从 HABTM 切换到 has_many :through 关系。 HABTM 表只能有两个外键字段,has_many :through 连接模型有一个主键,您可以在连接模型中添加任意数量的字段。

    Rails 指南:here

    当您希望将has_many : throughrelationship 用于您的连接模型时,一个很好的例子是在锻炼中添加锻炼:

    class Workout < ActiveRecord::Base
    
      has_many :workout_exercises, 
      has_many :exercises, :through => :workout_exercises
    
    class WorkoutExercise < ActiveRecord::Base
    
      belongs_to :exercise
      belongs_to :workout
    
    class Exercise < ActiveRecord::Base
    
      has_many :workout_exercises
      has_many :workouts, :through => :workout_exercises
    

    因此,现在锻炼中的锻炼可以具有重量,或者您想要与之关联的任何其他内容,只需将重量字段添加到连接表即可。

    【讨论】:

    • 谢谢,实际上我之前在提交表单时尝试过,结果相同。我想我缺少一些东西..
    • 任何想法..?感谢您的帮助,我对这个看似简单的事情感到沮丧..
    • 我不太熟悉那个宝石。如果你还需要帮助,我今晚会去看看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-11
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多