[英]rails association belongs_to
我知道麦粒肿在构建数据库的方式上一定是错误的,但是请花一点时间回答:我正在构建一个超级市场模型,其中1个用户有一个购物清单,每个清单有很多产品。 所以我要做的是:
class User < ActiveRecord::Base
has_many :lists
end
class List < ActiveRecord::Base
belongs_to :user
has_many :products
end
class Product < ActiveRecord::Base
????
end
列表中有几种产品,但产品不属于列表。 要让用户拥有很多列表,并且拥有很多产品的列表,我该怎么办? 问候,
有一个通过has_many链接它们的类。
class ListItem < ActiveRecord::Base
belongs_to :list
belongs_to :product
end
class List < ActiveRecord::Base
belongs_to :user
has_many :list_items
has_many :products, through: :list_items
end
您不需要额外的课程。 Rails可以通过has_and_belongs_to_many_association为您管理
在您的情况下,它将是:
class User < ActiveRecord::Base
has_many :lists
end
class List < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :products
end
class Product < ActiveRecord::Base
has_and_belongs_to_many :lists
end
当然,您需要在迁移中添加联接表:
create_table :lists_products, id: false do |t|
t.belongs_to :list
t.belongs_to :product
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.