簡體   English   中英

Active Record'到'關聯對象中的Access屬性

[英]Access attribute in Active Record 'through' association object

我使用Prole類(用於產品角色),在“多對多通過”關聯中有兩個類, UserProduct

class User < ActiveRecord::Base
  has_many :proles
  has_many :products, through: :proles
end

class Product < ActiveRecord::Base
  has_many :proles
  has_many :users, through: :proles
end

class Prole < ActiveRecord::Base
  # has an attribute called 'role'
end

prole有一個名為role的屬性,我想用它來限定用戶 - 產品關聯。

該關聯工作正常,但我無法弄清楚如何在創建關聯后訪問role屬性。 例如,如果我這樣做:

user.products << product

如何在剛剛創建的prole對象中訪問該屬性?

我想我可以遍歷prole對象並找到正確的對象,但我希望有一種更清潔的方式。

這可能嗎? 任何提示?

TIA。

我希望能有更直接的東西,但這里有一個可能的答案:

prole = Prole.find_by user_id: user.id, product_id: product.id

甚至更好

prole = user.proles.where("product_id = #{product.id}")

經過一些測試,看起來最簡單的方法是抓住剛創建的Prole對象,直接通過Prole模型查詢兩個外鍵,如您可能的答案所示。

Prole.find_by(user_id: user.id, product_id: product.id)

如果您希望它作為user對象的關聯,您可以使用includes方法來執行急切加載,但它仍將為相關user加載每個prole

# specifying proles: {product_id: product.id} in the where clause here 
# only limits users retrieved, not proles
user = User.includes(:proles).where(id: user.id) 
# eager-loaded prole array
user.proles.find { |prole| prole.product_id == product.id } 

有關詳細信息,請參閱此答案 但看起來你可能的答案是最干凈的方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM