简体   繁体   English

Rails协会归属于

[英]rails association belongs_to

I know sty must be wrong in the way I build my db but please take a minute answering this : I am building a supermarket model, where 1 user has a shopping list, each list has many products. 我知道麦粒肿在构建数据库的方式上一定是错误的,但是请花一点时间回答:我正在构建一个超级市场模型,其中1个用户有一个购物清单,每个清单有很多产品。 So what I do is : 所以我要做的是:

class User < ActiveRecord::Base
  has_many :lists
end

class List < ActiveRecord::Base
  belongs_to :user
  has_many :products
end

class Product < ActiveRecord::Base
  ????
end

A list has several products but products don't belong to lists. 列表中有几种产品,但产品不属于列表。 What should I do to have Users having many lists, and lists having many products ? 要让用户拥有很多列表,并且拥有很多产品的列表,我该怎么办? regards, 问候,

Have a class that links them via has_many through. 有一个通过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

You don't need an additional class. 您不需要额外的课程。 Rails can manage this for you with the has_and_belongs_to_many_association Rails可以通过has_and_belongs_to_many_association为您管理

In your case, it would be: 在您的情况下,它将是:

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

Of course, you need to add the join table in the migration: 当然,您需要在迁移中添加联接表:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM