[英]Accessing column stored in a join table - Rails
我有一個稱為ProductFeatures
聯接表,該表通過has_many: ..., through: product_features
聯接Product
和Feature
實例,並有一個名為rating
的附加列。
我想在Feature
上添加.rating
方法,該方法將基於調用它的特定產品實例返回一個評級浮動。 就像是:
Product.find(...).features.first.rating #=> should specific product_feature rating
我試過了:
.rating
。 這可行,但是每次我想要獲得特定的產品評分功能時,我都會使用product.id。 .caller
(與binding_of_caller或vanilla Ruby)從方法內部獲取調用者實例 ID,但是.caller
似乎無法讓我獲取調用實例ID,並且由於調用者將是規范的ExampleGroup
,因此在測試中也將失敗 您可以通過其他方式獲取這些數據。
- 我想在Feature上添加
#rating
方法,該方法將基於調用它的特定產品實例返回一個評級浮動。 就像是:
## Controller add this code snipped
get_feature = Product.find(...).features
rating(get_feature)
protected
def rating(get_all_feature)
all_rating = []
get_all_feature.each do |feature|
all_rating << feature.product_features.each { |u| u.rating }
end
all_rating
end
希望這對您有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.