【问题标题】:Rails/Arel User.where(:id => <Some Other Table>.user_id)Rails/Arel User.where(:id => <Some Other Table>.user_id)
【发布时间】:2013-04-25 08:05:05
【问题描述】:

嘿,我刚刚回到轨道上,我忘记了很多与某些协会合作所需的东西。

问题:

我有两个表,Customer 字段为 iduser_idUser 字段为 id。我想得到一个Users 的数组,这样Customeruser_id 就是idUser。我知道如何在 SQL 中执行此操作,但忘记了如何在 Ariel 中执行此操作。

编辑

所以我想我需要再解释一下。我正在接管一个现有的项目。用户和客户之间存在一对一的关系,但是只有一些用户具有相关的客户实体,因此调用user.customer 将在大多数情况下返回nil。我需要编辑一个当前列出所有用户的页面,但现在我只需要列出具有客户记录的用户。

之前的开发者已经创建了关系:

class Customer
  belongs_to :user, :class_name => "Refinery::User"
end

Refinery::User.class_eval do
  has_one :customer
end

我的控制器中有以下代码:

def index
  # i need to return an array of users, such that the only
  # users in this array are the ones with a non-nil customer.
  @users = Refinery::User.paginate(:page => params[:page])
end

任何帮助都会很棒,谢谢!

【问题讨论】:

    标签: ruby-on-rails associations arel


    【解决方案1】:

    您可以在两个类中定义关联,客户中的belongs_to 和用户中的has_many

    然后您就可以使用Users.find(id).customers 等。

    rails documentation 很好地解释了这一点 - 看看客户和订单的例子。

    更新 关注您的问题更新 - 尝试

    User.where("customer.id IS NOT NULL")
    

    @users = Refinery::User.where("customer.id IS NOT NULL").paginate(:page => params[:page])
    

    【讨论】:

    • 感谢您的帮助。客户的基础表是'cust'(我没有选择这个!)所以我尝试了你所说的以及.where("cust.id IS NOT NULL")并得到了这个错误:PG::Error: ERROR: missing FROM-clause entry for table "cust"customer的类名是否重要Refinery::Akouo::Customer?
    • 也许我需要在加入中包括客户?看起来这是 SQL 输出:SELECT COUNT(*) FROM "refinery_users" WHERE (customer.id IS NOT NULL)
    • 好的,但我必须在User之后添加:.includes(:customer)
    【解决方案2】:

    您不需要任何 Ariel 请求。

    用户:

    class User < ActiveRecord::Base
      has_many :customers
    end
    

    客户:

    class Customer < ActiveRecord::Base
      belongs_to :user
    end
    

    代码:

    customer = Customer.find(1)
    users = customer.users
    

    【讨论】:

      猜你喜欢
      • 2013-03-30
      • 2016-08-09
      • 1970-01-01
      • 2017-01-20
      • 1970-01-01
      • 2011-11-20
      • 2021-09-05
      • 2017-05-01
      • 1970-01-01
      相关资源
      最近更新 更多