class User < ActiveRecord::Base
has_many :vehicles
end
class Vehicle < ActiveRecord::Base
belongs_to :user
belongs_to :make
end
class Make < ActiveRecord::Base
has_many :vehicles
end
所以在MakesController#show
,我想顯示所有current_user
的車輛只有特定的品牌。有沒有辦法做到這一點在關聯像這樣:通過另一個關聯過濾has_many關聯結果?
current_user.vehicles.find_by_make(@make)
還是我不得不做這樣的事情:
Vehicle.find_by_user_and_make(current_user, @make)
?我知道第一種方法不起作用,但第二種方法感覺有點骯髒。
編輯: 道歉,我意識到我簡化了這個問題。我真的很想將Make上定義的類方法/範圍應用於關聯。調用ActiveRecord::Relation
方法,如where
,是相當微不足道的。匆匆趕過這個例子,但還有很多事情要比我想要做的一個簡單的where
電話,再次道歉。
'current_user.vehicles.where(:make_id => @make)'。查找將只取第一條記錄,而在哪裏取集合 – Zippie