這是我的模特,我正在嘗試撥打self.red
但它不起作用。這甚至有可能嗎?我可以從模型代碼中調用指定範圍嗎?
# Shirt has size and color
class Shirt < ActiveRecord::Base
scope :red, where(:color => 'red')
def find_red
return self.red
end
end
這是我的模特,我正在嘗試撥打self.red
但它不起作用。這甚至有可能嗎?我可以從模型代碼中調用指定範圍嗎?
# Shirt has size and color
class Shirt < ActiveRecord::Base
scope :red, where(:color => 'red')
def find_red
return self.red
end
end
嘗試Shirt.red
self.red
將是一個對象的方法。 scope :red
已經是一種類方法,因此您不必編寫方法find_red
來執行查詢,Shirt.red
已經可以做到這一點。
您正在通過返回self.red調用一個實例方法。
你想達到什麼是
def find_red
return Shirt.red
end
你可能會發現調用self.class.red
最好在其他答案提出的Shirt.red
。它不太好讀,但它的優點是,如果類名稱每改變一次你的代碼就可以保持不變。
以爲我會拋出與此線程有關的情況,以防有人絆倒它。
您應該遠離實例方法中的調用範圍。你會很快發現自己調試性能問題。無論是否包含關係,範圍將始終返回到數據庫。
I.e.
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