如何在 Rails 中使用 :through 关联的连接表上设置的条件进行查找?
我有以下模型:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这里回答我自己的问题,Rails 实际上允许您在关联本身上设置条件。因此,例如,在我的用户模型中,我会将
has_many
关联修改为:非常简洁。 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: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...!
抱歉,这是快速猜测。抱歉,如果这不对。
Sorry, this is quick guess. sorry if this isn't right.