在 Ruby on Rails 中指定关系的条件

发布于 2024-11-09 23:17:16 字数 544 浏览 0 评论 0原文

我有以下内容

has_many :administrators, :class_name => "User", :conditions => "role_id = 4"

,它工作正常,但我不想使用外键,而是

"role_id = 4"

更愿意指定角色表中与该外键相关的实际角色字符串,例如“Admin”

UPDATE:

SELECT *
FROM users u, roles r
WHERE u.role_id = r.id
AND r.role = "Admin"

UPDATE 2

我不能这样做像这样的东西:(这不起作用,但说明了我正在尝试做的事情)

has_many :administrators, :class_name => "User", :conditions => { :role => {:name => "Admin"}}

I have the following

has_many :administrators, :class_name => "User", :conditions => "role_id = 4"

and it works fine, but instead of using the foreign key

"role_id = 4"

I would prefer to specify the actual role string in the roles table, that that foreign key relates to, e.g "Admin"

UPDATE:

SELECT *
FROM users u, roles r
WHERE u.role_id = r.id
AND r.role = "Admin"

UPDATE 2

can't I do something like this: (this doesn't work, but illustrates what I am trying to do)

has_many :administrators, :class_name => "User", :conditions => { :role => {:name => "Admin"}}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不寐倦长更 2024-11-16 23:17:16

想通了:

has_many :administrators, :class_name => "User", :conditions => {:roles => {:name => "Admin"}}, :include => :role

Figured it out:

has_many :administrators, :class_name => "User", :conditions => {:roles => {:name => "Admin"}}, :include => :role
酒与心事 2024-11-16 23:17:16

尝试一下

has_many :administrators, :class_name => "User", :conditions => "role_id = #{Role.find(:name => 'Admin')}" 

假设角色表有一个相应的模型。您使用的是特定框架还是自制授权?

what about trying

has_many :administrators, :class_name => "User", :conditions => "role_id = #{Role.find(:name => 'Admin')}" 

Assuming the role table had a corresponding model. are you using a specific framework, or home baked authorization?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文