开发者_运维技巧#!ruby
class Car < ActiveRecord::Base
belongs_to :user
end
@cars = Car.where(:user_id => current_user.id).limit(10)
I want to create a scope, how can I use the association :user in the scope?
(rails3)
So, in your model:
scope :foo, lambda {|u| where( :user_id => u ).limit(10) }
...which you can then call from your controller with:
Car.foo(current_user)
Try:
Car.join(:user).where(:user_id => current_user.id).limit(10)
Update:
in your model
def self.with_user(user)
join(:user).where(:user_id => user.id)
end
in your controller
Car.with_user(current_user).limit(10)
精彩评论