简体   繁体   English

访问存储在联接表中的列-Rails

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

I have a join table called ProductFeatures which joins Product and Feature instances via has_many: ..., through: product_features , and has an additional column called rating . 我有一个称为ProductFeatures联接表,该表通过has_many: ..., through: product_features联接ProductFeature实例,并有一个名为rating的附加列。

I want to add .rating method on Feature which will return a rating float based on specific product instance that is calling it. 我想在Feature上添加.rating方法,该方法将基于调用它的特定产品实例返回一个评级浮动。 Something like: 就像是:

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

I've tried: 我试过了:

  • passing caller_id as an argument to .rating . 传递caller_id作为参数.rating This works, but makes me use product.id each time I want to get a specific product rating feature. 这可行,但是每次我想要获得特定的产品评分功能时,我都会使用product.id。
  • Obtaining a caller instance id from inside the method using .caller (with binding_of_caller , or vanilla Ruby), but .caller does not seem to let me get a calling instance id, and would also fail in tests as the caller would be the spec's ExampleGroup 使用.caller (与binding_of_caller或vanilla Ruby)从方法内部获取调用者实例 ID,但是.caller似乎无法让我获取调用实例ID,并且由于调用者将是规范的ExampleGroup ,因此在测试中也将失败

You can get these data with other way. 您可以通过其他方式获取这些数据。

  • I want to add #rating method on Feature which will return a rating float based on specific product instance that is calling it. 我想在Feature上添加#rating方法,该方法将基于调用它的特定产品实例返回一个评级浮动。 Something like: 就像是:
## 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

Hope this help you! 希望这对您有所帮助!

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

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