2013-04-11 83 views
0
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电话,再次道歉。

+0

'current_user.vehicles.where(:make_id => @make)'。查找将只取第一条记录,而在哪里取集合 – Zippie

回答

0

你想

current_user.vehicles.where(make_id: @make) 

由@Zippie

1

ponted出来你也可以做

current_user.vehicles.find_all_by_make(@make)