【问题标题】:Many model records in has_many-relationship columnshas_many-relationship 列中有许多模型记录
【发布时间】:2013-01-16 03:41:55
【问题描述】:

我有一个Brand 模型和一个Price 模型,因此:

brand.rb

class Brand < ActiveRecord::Base
  attr_accessible :name, :a4_single, :a4_double, :a3_double, :two_a3_double
  has_many :prices, :dependent => :destroy
end

price.rb

class Price < Brand
  attr_accessible :type, :quantity, :price, :brand_id
  belongs_to :brand
end

我希望能够在 每个 产品列中插入 多个 Price 记录,例如,:a4_single 中的 10 条 Price 记录,@ 中的 8 条记录987654328@,:a3_double 中有两个,:two_a3_double 中有八个。

我只是猜测上面定义的has_many关系是正确的,我真的不知道如何从这里着手。

【问题讨论】:

    标签: ruby-on-rails-3 has-many belongs-to


    【解决方案1】:

    你不应该再继续下去了。

    做这样的事情

    class Brand < ActiveRecord::Base
      has_many :brand_prices
      has_many :prices, :through => :brand_prices
      attr_accessible :name
    end
    
    class Price < ActiveRecord::Base
      has_many :brand_prices
      has_many :brands, :through => :brand_prices
      attr_accessible :price, :quantity, :type
    end
    
    class BrandPrice < ActiveRecord::Base
      belongs_to :brand
      belongs_to :price
    end
    

    【讨论】:

    • 这个解决方案是有道理的,但它让我想知道一些事情:我已经嵌套了表单/模型,并在它们之间建立了has_many, :through 关系。首先,我如何将Price 实例与特定的Brand 列相关联?我想过做一个Brand.column_name.eachcollection_select 的东西,但这似乎可以证明是不符合Rails 的。其次,保存定价信息有效,但edit 屏幕没有显示任何值,尽管它们存储在数据库中。有什么想法吗?
    • 我一直在以错误的方式思考这个问题,但您确实帮助我找到了解决方案。我在另一个模型中将Brand 列信息加倍。危机结束。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 2016-08-05
    • 2017-10-17
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多