Ruby on rails Rails/Arel User.where(:id=>;<;其他一些表>;.User\u id)
嘿,我刚刚回到rails,我已经忘记了与一些协会合作需要的很多东西 问题: 我有两个表,Ruby on rails Rails/Arel User.where(:id=>;<;其他一些表>;.User\u id),ruby-on-rails,associations,arel,Ruby On Rails,Associations,Arel,嘿,我刚刚回到rails,我已经忘记了与一些协会合作需要的很多东西 问题: 我有两个表,Customer带字段id和user\u id和user带字段id。我想获得一个用户数组,这样客户的用户id就是用户的id。我知道如何在SQL中执行此操作,但忘记了如何在Ariel中执行此操作 编辑 所以我想我需要再解释一下。我正在接管一个现有的项目。用户和客户之间存在一对一的关系,但是只有一些用户具有相关的客户实体,因此调用user.customer在大多数情况下将返回nil。我需要编辑当前列出所有用户的页
Customer
带字段id
和user\u id
和user
带字段id
。我想获得一个用户数组
,这样客户的用户id
就是用户的id
。我知道如何在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
任何帮助都会很好,谢谢 您可以在两个类中定义关联,在customer中属于
,在user中有许多
然后,您将能够使用Users.find(id).customers
等
下面的例子很好地解释了这一点——看看客户和订单的例子
更新
在您的问题更新后-尝试
User.where("customer.id IS NOT NULL")
或
你不需要任何Ariel的要求
用户:
class User < ActiveRecord::Base
has_many :customers
end
谢谢你的帮助。customer的基础表是'cust'(我没有选择它!),所以我尝试了您所说的以及。其中(“cust.id不是NULL”)
并得到了以下错误:PG::error:error:表“cust”的子句条目中缺少
如果customer
的类名是Refinery::Akouo::customer
,这是否重要?也许我需要在一个联接中包含客户?看起来这是SQL输出:SELECT COUNT(*)FROM“refinery\u users”,其中(customer.id不为NULL)
ok这可以工作,但我必须添加:。包括(:customer)
紧跟在User
class User < ActiveRecord::Base
has_many :customers
end
class Customer < ActiveRecord::Base
belongs_to :user
end
customer = Customer.find(1)
users = customer.users