一种方法可以多次通过
我有一个类别、一个子类别和一个产品模型。
我:
Category has_many Subcategories
Subcategory has_many Products
Subcategory belongs_to Category
Product belongs_to Subcategory
有没有办法拥有类似的东西
Category has_many Projects through Subcategories
?
“正常”rails 方式不起作用,因为“子类别”不属于产品,因此产品没有 subcategory_id 字段。相反,我需要查询类似于
SELECT * FROM products WHERE id IN category.subcategory_ids
是否有办法做到这一点?
谢谢,
尼古拉斯·霍克·伊萨萨
I have a Category, a Subcategory and a Product model.
I have:
Category has_many Subcategories
Subcategory has_many Products
Subcategory belongs_to Category
Product belongs_to Subcategory
Is there a way to have something like
Category has_many Projects through Subcategories
?
The 'normal' rails way wouldn't work because "subcategory" doesn't belongs to product so product does not have a subcategory_id field. Instead, I need the query to be something like
SELECT * FROM products WHERE id IN category.subcategory_ids
Is there a way to do that?
Thanks,
Nicolás Hock Isaza
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您以“正常”Ruby on Rails 方式执行此操作,您描述的数据库将如下所示。如果您的数据库不是这样构造的,我建议您阅读有关如何在 Ruby on Rails 中完成关联的更多信息,因为这是正确的方法(并且您应该在您的数据库中使用
t.references :category
迁移,因为它的设计目的是为了让您的参考资料变得更容易)。以此作为您的数据库结构,
has_many :products, :through => subcategories
适用于Category
模型。Category.rb
Subcategory.rb
Product.rb
ruby script\console
If you do this the 'normal' Ruby on Rails way, the database you described would look something like this. If your database isn't structured like this, I suggest reading more about how associations are done for in Ruby on Rails because this is the right way (and you should be using
t.references :category
in your migration since it was designed to make it easy to not mess your references up).With this as your database structure, the
has_many :products, :through => subcategories
works for theCategory
model.Category.rb
Subcategory.rb
Product.rb
ruby script\console