我可以从刚刚定义的模型代码中调用命名范围吗?

时间:2011-01-10 01:21:29

标签: ruby-on-rails

这是我的模型,我试图致电self.red,但它不起作用。这甚至可能吗?

# Shirt has size and color
class Shirt < ActiveRecord::Base
    scope :red, where(:color => 'red')

    def find_red
        return self.red
    end
end

4 个答案:

答案 0 :(得分:9)

尝试Shirt.red
self.red将是一种对象方法。 scope :red已经是一个类方法,因此您不必编写方法find_red来执行查询,Shirt.red就已经这样做了。

答案 1 :(得分:2)

您可能会发现呼叫self.class.red优于其他答案中提出的Shirt.red。阅读并不是一件好事,但它的优势在于,如果每个更改都为您的代码命名,那么您的代码可以保持不变。

答案 2 :(得分:1)

您通过返回self.red来调用实例方法。

您想要实现的是

def find_red
    return Shirt.red
end

答案 3 :(得分:0)

如果有人偶然发现它,我想把它扔到那里与此线程有关。

您应该远离实例方法中的调用范围。您很快就会发现自己正在调试性能问题。无论是否包含关系,范围都将始终返回数据库。

即。

class Show
  has_many :episodes

  def awesome_episodes
    episodes.awesome # THIS IS BAD!!
    # should stay in ruby land with episodes.select { |ep| ep.status == "awesome" } 
    # OR push a method #awesome? to the episode class and then the 
    # syntax becomes nicer: episodes.select(&:awesome?)
    # This way, the onus is on the caller to include the relationship 
  end
end

class Episode
  belongs_to :show

  scope :awesome, ()-> { where(status: 'awesome') }
end

shows = Show.includes(:episodes)

shows.map do |show|
  show.awesome_episodes # fires a query every loop
end