开发者

How to retrieve users given user_level in rails

Here is two models: user and user_level. User has_many user_levels and user-level belongs to user.

class user < ActiveRecord::Base
  has_many :user_level
end

class UserLevel < ActiveRecord::Base

  belongs_to :user
end

UserLevel.find_by_role('sales') will retrieve all record (w/ user_id) of role sales. How to retrieve user email given user_level with role 'sal开发者_开发技巧es'?

Thanks.


User.joins(:user_levels).where(:user_levels => { :role => "sales"}).select("email")

or

UserLevel.joins(:user).where(:role => "sales").select("email")

update

UserLevel.find_by_role("sales").users


You may have the associations backwards and actually want:

class User < ActiveRecord::Base
  belongs_to :user_level
end
class UserLevel < ActiveRecord::Base
  has_many :users
end

Then:
@users = UserLevel.find_by_role('sales').users
You can then iterate over the @user collection and use the email within the iterations.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜