【问题标题】:How can I do a find in Rails with conditions set on the join table of a :through association?如何在 Rails 中使用 :through 关联的连接表上设置的条件进行查找?
【发布时间】:2011-04-27 14:48:07
【问题描述】:

我有以下型号:

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

我希望能够仅显示用户有权访问的任务(即,Permissions 表中的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])

有人知道正确的方法吗?

【问题讨论】:

    标签: ruby-on-rails associations conditional-statements has-many-through


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      相当整洁。 Trip 建议的解决方案也有效(但至少对于 MySQL,不应引用 'true')。我发誓我试过那个...!

      【讨论】:

        猜你喜欢
        • 2013-04-22
        • 1970-01-01
        • 2021-10-01
        • 2021-11-24
        • 2011-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-29
        相关资源
        最近更新 更多