【发布时间】:2013-01-22 15:56:35
【问题描述】:
我有一个 has_one 关联:
has_one 关联用户 -> 客户模型
用户将拥有 customer_id 还是客户将拥有 user_id 属性?
其他问题:在我的 _form 中,我想对所有未与客户关联的用户进行选择/选项,这是最好的方法吗?
非常感谢。
【问题讨论】:
标签: ruby-on-rails view associations
我有一个 has_one 关联:
has_one 关联用户 -> 客户模型
用户将拥有 customer_id 还是客户将拥有 user_id 属性?
其他问题:在我的 _form 中,我想对所有未与客户关联的用户进行选择/选项,这是最好的方法吗?
非常感谢。
【问题讨论】:
标签: ruby-on-rails view associations
_id 字段始终在具有belongs_to 的模型中,并引用其他表名。
class Customer < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_one :customer
end
在这种情况下,customers 表将有一个 user_id 字段。
对于第二个问题,使用外连接在 SQL 中找到缺失值。 你想要的 SQL 是
select
from users
left outer join customers on users.id = customers.user_id
where customers.id is null
在 ActiveRecord 中,为您的 User 类添加一个范围。
在 Rails 3.x 中:
class User < ActiveRecord::Base
has_one :customer
scope :missing_customer,
includes(:customer).where("customers.id is null")
end
在 Rails 2.3.x 中:
class User < ActiveRecord::Base
named_scope :missing_customer,
{ :joins => "left outer join customers on users.id = customers.user_id",
:conditions => "customers.id is null" }
end
【讨论】: