根据关系创建范围

时间:2011-02-22 18:13:10

标签: ruby-on-rails ruby scope relationship

我正在使用Rails 3.0.4和Ruby 1.9.2

我正在尝试创建一个名为role的作用域,该作用域接受一个角色字符串,并返回User作为其中一个角色的所有role条记录。

问题是UserRole有HABTM关系,我真的不知道如何在常规User.where()语句中访问此信息。

这就是我的想法:

scope :role, lamda {|role| where {|user| user.role? role} }

(角色?是我编写的一种方法,只检查用户是否属于该角色)

有没有办法从那里传递用户对象?还是能完成同样事情的东西?

谢谢。

1 个答案:

答案 0 :(得分:3)

如果role只是用户模型中的一个字段:

scope :with_role, lamda{|role_name| where(:role => role_name) }
User.with_role "Member"

如果角色是单独的模型而User belongs_to :role。角色也有标题字段:

scope :with_role, lamda{|role_name| includes(:role).where(:roles => {:title => role_name}) }
User.with_role "Member" # the same usage

UPD 1

如果User has_many :roles您应该使用用户模型方法:

class User < ActiveRecord::Base
  has_many :roles

  def self.with_role(role_name)
    Role.where(:name => role_name).first.users # hope title is validated uniq
  end
end

=&GT; User.with_role( “成员”)

或使用范围:

scope :with_role, lambda{ |role| joins(:roles).where(:roles => {:name => role}) }
相关问题