开发者

Active record associations for a User and has many addresses with one marked as primary

I am trying to setup my rails models where I have a User and they have many addresses but one is their primary address. I want to be able to access it like so, User开发者_开发百科.first.primary_address_id and also User.first.primary_address to get the associated Address model.

Is there a "rails way" to set this up?

I know I could create a primary_address_id field for User and populate it in an AR callback. But that wouldn't let me do something like User.first.primary_address

Or can I create associations as "User has_many Addresses" as well as "User has_one Address"?? or something along those lines?


I know I could create a primary_address_id field for User and populate it in an AR callback. But that wouldn't let me do something like User.first.primary_address

This is the correct way to do it.

User.first.primary_address

would return the first user's primary address if they had one or nil if they didn't.

#user.rb
has_one :primary_address

#address.rb
attr_accessor :primary #this allows you to have a primary field of the address form

after_save :check_if_primary

def check_if_primary
   user.update_attribute(:primary_address, self) if primary
end


One simple way would be to have a primary_address boolean column in your Address model.

To access the primary address object of the user you could define a primary_address method in the User model :

class User < ActiveRecord::Base
  def primary_address
    addresses.where(:primary_address => true).first
  end
end

Since, the primary_address method is an instance method, it would allow you to do

User.first.primary_address
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜