范围使用参数并访问多对多关系

时间:2014-11-17 23:17:14

标签: ruby-on-rails ruby scope many-to-many

您好我在使用rails关系时遇到问题。

我有类跟随,我希望能够将参数传递给方法或范围,并返回任何资源产品等于参数。

class Product < ActiveRecord::Base
  attr_accessible :title

  has_and_belongs_to_many :resources   
end


class Resource < ActiveRecord::Base
  has_and_belongs_to_many :products

  scope :has_product, ->(product) { joins(:products).where(products: { title: product }) }

  #OR

  def self.has_product(product)
    self.products.each do |p|
      return self if p.title == product 
    end
  end
end

class Report < Resource
end

ERROR

NoMethodError: undefined method `has_product' for #<Report:0x007fa859aa3080>
from /Users/x/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/activemodel-3.2.13/lib/active_model/attribute_methods.rb:407:in `method_missing'

请帮我看看我缺少的东西

1 个答案:

答案 0 :(得分:1)

您无法将products作为类方法调用,因为它的实例方法(用法:Resource.last.products)。这样,同样适用于has_product?方法:

class Resource < ActiveRecord::Base
  has_and_belongs_to_many :products

  def has_product?(product)
    product_ids.include?(product.id)
  end

end

用法:

product = Product.first
Resource.last.has_product?(product) # => true or false

修改

要回答这个问题,要获得产品使用范围的任何资源,例如:

scope :for_product, ->(product) { joins(:products).where(products: { title: product.title }) }

用法:

product = Product.first
Resource.for_product(product) # => ActiveRecord::Relation with products