[英]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.