Ruby on rails 多个与同一模型有多个关联
我在一个系统中工作,该系统将列出产品的买卖情况。由于这些买卖的清单具有相同的信息-单价和数量-我只考虑制作两个模型:项目和清单。但是,如何使2在项目和列表之间有许多关联?我在考虑多态关联,但我没能让它起作用 迁移Ruby on rails 多个与同一模型有多个关联,ruby-on-rails,Ruby On Rails,我在一个系统中工作,该系统将列出产品的买卖情况。由于这些买卖的清单具有相同的信息-单价和数量-我只考虑制作两个模型:项目和清单。但是,如何使2在项目和列表之间有许多关联?我在考虑多态关联,但我没能让它起作用 迁移 create_table :listings do |t| t.integer :unit_price t.integer :quantity t.references :listable, polymorphic: true, index: true t.timest
create_table :listings do |t|
t.integer :unit_price
t.integer :quantity
t.references :listable, polymorphic: true, index: true
t.timestamps
end
项目1.rb
has_many :buys, as: :listable
has_many :sells, as: :listable
listing.rb
belongs_to :listable, polymorphic: true
我尝试在控制台上运行此操作,但它不起作用:
rails c
Item.create!
Item.first.buys
调用此错误
NameError: uninitialized constant Item::Buy
在列表迁移中:
create_table :listings do |t|
t.integer :unit_price
t.integer :quantity
t.integer :item_id
t.integer :type
t.timestamps
end
现在在项目模型中:
类型字段用作列表的指示:对于购买,值为0,对于出售,值为1。多态关联的工作方式正好相反。
class Item < ActiveRecord::Base
has_many :buys, -> { where "type = 0" }, class_name: "Listing"
has_many :sells, -> { where "type = 1" }, class_name: "Listing"
end