Rails - 一个用户多个地址

时间:2013-06-21 00:55:09

标签: ruby-on-rails

我有一个用户模型

class User < ActiveRecord::Base
    attr_accessible :email, :password, :password_confirmation, :remember_me, :first_name, :last_name, :shipping_address_id; :billing_address_id
end

和地址模型

class Address < ActiveRecord::Base
    attr_accessible :country_id, :city, :plz, :street, :streetnr, :first_name, :last_name
end

我想通过有效记录关联做什么:每个用户都有billing_address和shipping_address。我可以创建一个关系,以便我可以像user.billing_address一样访问它们吗?

2 个答案:

答案 0 :(得分:6)

您可以在belongs_to association中添加类名和外键。

class User < ActiveRecord::Base
    attr_accessible :email, :password, :password_confirmation, :remember_me, :first_name, :last_name, :shipping_address_id; :billing_address_id
    belongs_to :billing_address, class_name: :Address, foreign_key: :billing_address_id
    belongs_to :shipping_address, class_name: :Address, foreign_key: :shipping_address_id
end

然后您可以访问

等地址
user.billing_address
user.shipping_address

答案 1 :(得分:1)

@kengo提到的方法应该有效,但更合适的方法是

class User < ActiveRecord::Base
  attr_attr_accessible :email, :password, :password_confirmation, :remember_me, :first_name, :last_name, :shipping_address_attributes; :billing_address_attributes
  has_one :billing_address, :class_name => 'Address'
  has_one :shipping_address, :class_name => 'Address'
  accepts_nested_attributes_for :billing_address
  accepts_nested_attributes_for :shipping_address
end

通过这种方式,您可以使用嵌套表单接受运费和帐单邮寄地址的值。此外,您也将满足您的基本要求。