开发者

Creating a scope based off of a relation

开发者 https://www.devze.com 2023-02-12 11:33 出处:网络
I\'m 开发者_如何学Pythonusing Rails 3.0.4 and Ruby 1.9.2 I\'m trying to create a scope called role which takes a role string and returns all of the User records that have role as one of their roles.

I'm 开发者_如何学Pythonusing Rails 3.0.4 and Ruby 1.9.2

I'm trying to create a scope called role which takes a role string and returns all of the User records that have role as one of their roles.

The problem is User and Role have a HABTM relationship, and I don't really know how to access this information in a regular User.where() statement.

This is what I'm thinking:

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

(role? is a method I wrote that just checks if a user belongs to that role)

Is there a way to pass the user object like that from where? Or something that accomplishes the same thing?

Thank you.


If role is just a field in user model:

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

If role is a separate model and User belongs_to :role. Also Role has got title field:

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

UPD 1

If User has_many :roles you should use User model method:

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

=> User.with_role("Member")

or using scope:

scope :with_role, lambda{ |role| joins(:roles).where(:roles => {:name => role}) }
0

精彩评论

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