如何在 Rails 中使用 :through 关联的连接表上设置的条件进行查找?

发布于 2024-09-28 00:51:00 字数 718 浏览 11 评论 0原文

我有以下模型:

class User < ActiveRecord::Base
  has_many :permissions
  has_many :tasks, :through => :permissions

class Task < ActiveRecord::Base
  has_many :permissions
  has_many :users, :through => :permissions

class Permission < ActiveRecord::Base
  belongs_to :task
  belongs_to :user

我希望能够仅显示用户有权访问的任务(即,在 中将 read 标志设置为 true权限表)。我可以通过以下查询来完成此操作,但对我来说这似乎不太像 Rails-y:

@user = current_user
@tasks = @user.tasks.find_by_sql(["SELECT * FROM tasks INNER JOIN permissions ON tasks.id = permissions.task_id WHERE permissions.read = true AND permissions.user_id = ?", @user.id])

有人知道执行此操作的正确方法吗?

I have the following models:

class User < ActiveRecord::Base
  has_many :permissions
  has_many :tasks, :through => :permissions

class Task < ActiveRecord::Base
  has_many :permissions
  has_many :users, :through => :permissions

class Permission < ActiveRecord::Base
  belongs_to :task
  belongs_to :user

I want to be able to display only tasks which a user has access to (i.e., the read flag is set to true in the Permissions table). I can accomplish this with the following query, but it doesn't seem very Rails-y to me:

@user = current_user
@tasks = @user.tasks.find_by_sql(["SELECT * FROM tasks INNER JOIN permissions ON tasks.id = permissions.task_id WHERE permissions.read = true AND permissions.user_id = ?", @user.id])

Anyone know the right way to do this?

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

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

发布评论

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

评论(2

酒废 2024-10-05 00:51:00

在这里回答我自己的问题,Rails 实际上允许您在关联本身上设置条件。因此,例如,在我的用户模型中,我会将 has_many 关联修改为:

has_many :tasks, :through => :permissions, :conditions => 'permissions.read = true'

非常简洁。 Trip 建议的解决方案也有效(除了,至少对于 MySQL,不应引用“true”)。我发誓我试过了……!

Answering my own question here, Rails actually lets you set conditions on the association itself. So, e.g., in my User model, I'd modify that has_many association to be:

has_many :tasks, :through => :permissions, :conditions => 'permissions.read = true'

Pretty neat. The solution suggested by Trip also works (except that, for MySQL at least, 'true' should not be quoted). I swear I tried that one...!

半仙 2024-10-05 00:51:00

抱歉,这是快速猜测。抱歉,如果这不对。

@user.tasks.find(:all, :conditions => "permissions.read = 'true' ")

Sorry, this is quick guess. sorry if this isn't right.

@user.tasks.find(:all, :conditions => "permissions.read = 'true' ")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文