简体   繁体   English

Rails-HABTM和has_many通过的不良影响一起使用吗?

[英]Rails - Ill effects of HABTM and has_many through used together?

I have an association, 我有一个联系,

Shop habtm Products
Product habtm Shops

Shop belongs_to Merchant

For convenience, I also declared a 为了方便起见,我还宣布了

Merchant has_many :products, :through=>:shops

In my products controller, 在我的产品控制器中

@products = current_user.merchant.products

When I <%=debug @products %> , the collection includes multiple copies of the same object. 当我<%=debug @products %> ,集合包含同一对象的多个副本。

Is this normal or have I screwed myself by declaring HABTM and has_many through together? 这是正常现象还是我通过同时声明HABTM和has_many来搞砸自己?

If this is normal, is there a way to call the products without duplicate entries appearing? 如果正常,是否可以在没有重复条目出现的情况下调用产品?

Thank you. 谢谢。

Update 更新资料

I realized this should be okay because the habtm is between Shops and Products . 我意识到这一点应该没问题,因为habtm之间ShopsProducts The Merchant has_many Products . Merchant has_many Products Is it possible to call something like a product.merchant without setting a foreign key inside the product model? 是否可以在产品模型内部未设置外键的情况下调用诸如product.merchant类的东西?

如果您的商人有一些商店提供相同的产品,这是正常的行为。

您可以使用distinct

@products = current_user.merchant.products.distinct(:product_id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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