Rails:除了 has_many 关联之外,如何使用 own_to 关联进行引用?
设置如下: 一个用户可以有多个地址,但至少其中一个是主地址。用户表中的外键应用作指向主地址记录的指针。
class User < ActiveRecord::Base
has_many :addresses
belongs_to :main_address, :class_name => 'Address', :foreign_key => 'main_address_id'
accepts_nested_attributes_for :main_address
end
class Address < ActiveRecord::Base
belongs_to :user # used for has_many
end
此设置仅适用于读取 main_address。但构建是一个问题,例如以具有嵌套属性(地址字段)的复杂形式使用它来创建。
我收到以下错误: SQLite3::ConstraintException:addresses.user_id 可能不为 NULL:
问题是,该地址是通过 main_address.build
构建的,并且该地址未接收外键 < code>user_id 因为它是通过 main_address
构建的。
我不知道:( 如何使用belongs_to关联正确引用has_many关联?
Following set-up: A user can have many addresses, but at least one of them is the main address. A foreign key in the user table should be used as a pointer to the main address record.
class User < ActiveRecord::Base
has_many :addresses
belongs_to :main_address, :class_name => 'Address', :foreign_key => 'main_address_id'
accepts_nested_attributes_for :main_address
end
class Address < ActiveRecord::Base
belongs_to :user # used for has_many
end
This Set-Up works for just reading the main_address. But building is a problem, for example by using it in a complex form with nested attributes (Address fields) for creating.
I get the following error:SQLite3::ConstraintException: addresses.user_id may not be NULL:
The problem is, that the address is build via main_address.build
and the address does not receive the foreign key user_id
because it is build via main_address
.
I have no idea :(
How can I use a belongs_to association for referencing a has_many association correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然我同意 lukewendling 的观点,但另一种方法是在
Address
中建立关联(到User
),然后使用before_save
更新>user_id
如果需要的话。像这样的东西:Although I agree with lukewendling, the alternative is to establish an association in
Address
(toUser
) and then use abefore_save
to update theuser_id
if needed. Something like this:您对“真实”世界的建模似乎有点奇怪,同样,您试图建立的关联也很复杂。用户似乎不属于 MainAddress,就像用户不属于其 PrimaryVehicle 一样。为什么不在地址模型上使用布尔值,例如 Address#primary? ?
Your modeling of the 'real' world seems a bit odd, and similarly, the association you're trying to make is complicated. A User doesn't seem to belong to an MainAddress any more than a User belongs to her PrimaryVehicle. Why not have a boolean on the Address model such as Address#primary? ?