简体   繁体   English

如何在Rails中通过:through关联的联接表设置条件的查找?

[英]How can I do a find in Rails with conditions set on the join table of a :through association?

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 (ie, the read flag is set to true in the Permissions table). 我希望仅显示用户有权访问的任务(即,在“ Permissions表中将“ read标志设置为true )。 I can accomplish this with the following query, but it doesn't seem very Rails-y to me: 我可以使用以下查询来完成此操作,但对我而言似乎并不十分Rails:

@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? 有人知道正确的方法吗?

Answering my own question here, Rails actually lets you set conditions on the association itself. 在这里回答我自己的问题时,Rails实际上允许您在关联本身上设置条件。 So, eg, in my User model, I'd modify that has_many association to be: 因此,例如,在我的用户模型中,我将has_many关联修改为:

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). Trip建议的解决方案也可以使用(除了,至少对于MySQL,不应引用“ true”)。 I swear I tried that one...! 我发誓我尝试过一个...!

Sorry, this is quick guess. 抱歉,这是个快速猜测。 sorry if this isn't right. 抱歉,如果这不正确。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何基于联接表为has_many:through关联设置default_scope? - How do I set a default_scope for a has_many :through association based on the join table? 我可以加入没有关联的表吗? (rails / sql) - Can I join a table with no association? (rails/sql) 如何在Ruby On Rails中设置:through ActiveRecord关联? - How do I set up a :through ActiveRecord association in Ruby On Rails? Rails 4-如何通过has_many关联在同一列上具有多个条件来查询集合? - Rails 4 - how do I query on a collection through a has_many association with multiple conditions on the same columns? Rails has_many:through-&gt;如何设置一个关联以从多个联接模型中提取? - Rails has_many :through --> How do you set up an association to pull from multiple join models? Rails:通过连接表获取关联计数 - Rails: get count of association through join table 如何通过连接表根据关联查找记录数 - How to find number of records based on association through join table Rails通过连接表获得关联计数 - Rails get count of association through join table 我是否需要has_many的联接表:通过关联? - Do I need a join table for a has_many :through association? 如何通过联接表在Rails中按计数分组和排序? - How do I group by and order by count in Rails through a join table?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM