开发者

How to reference a belongs_to association in a scope?

开发者 https://www.devze.com 2023-02-25 11:03 出处:网络
开发者_运维技巧#!ruby class Car < ActiveRecord::Base belongs_to:user end @cars = Car.where(:user_id => current_user.id).limit(10)
开发者_运维技巧#!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)
0

精彩评论

暂无评论...
验证码 换一张
取 消