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开发者_JS百科(["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. 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...!
Sorry, this is quick guess. sorry if this isn't right.
@user.tasks.find(:all, :conditions => "permissions.read = 'true' ")
精彩评论