开发者

Rails: How to use a belongs_to association for referencing in addition to a has_many association?

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 Ad开发者_开发技巧dress < 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?


Although I agree with lukewendling, the alternative is to establish an association in Address (to User) and then use a before_save to update the user_id if needed. Something like this:

has_one :main_user, :class_name => 'User', :foreign_key => 'main_address_id'

before_save :update_user_id

def update_user_id
  if main_user.present?
    self.user_id = main_user.id
  end
end


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? ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜