簡體   English   中英

訪問存儲在聯接表中的列-Rails

[英]Accessing column stored in a join table - Rails

我有一個稱為ProductFeatures聯接表,該表通過has_many: ..., through: product_features聯接ProductFeature實例,並有一個名為rating的附加列。

我想在Feature上添加.rating方法,該方法將基於調用它的特定產品實例返回一個評級浮動。 就像是:

Product.find(...).features.first.rating #=> should specific product_feature rating

我試過了:

  • 傳遞caller_id作為參數.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.

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