我有以下设置:
架构.rb
ActiveRecord::Schema.define(version: 20130923235150) do
create_table "addresses", force: true do |t|
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "user_addresses", force: true do |t|
t.integer "user_id"
t.integer "address_id"
t.string "purpose"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", force: true do |t|
t.datetime "created_at"
t.datetime "updated_at"
end
end
用户.rb:
class User < ActiveRecord::Base
has_one :user_address
has_one :primary_shipping_address, through: :user_address, class_name: :UserAddress, source: :address
has_one :primary_billing_address, through: :user_address, class_name: :UserAddress, source: :address
end
地址.rb:
class Address < ActiveRecord::Base
has_one :user_address
has_one :primary_shipping_user, through: :user_address, class_name: :UserAddress, source: :user
has_one :primary_billing_user, through: :user_address, class_name: :UserAddress, source: :user
end
用户地址.rb:
class UserAddress < ActiveRecord::Base
belongs_to :user
belongs_to :address
end
当有人这样做时user.primary_billing_address = address
,我希望连接模型实例将“计费”设置为其目的。与运输和“运输”类似。前任。
irb(main):013:0> u = User.new
=> #<User id: nil, created_at: nil, updated_at: nil>
irb(main):014:0> a = Address.create
=> #<Address id: 3, created_at: "2013-09-24 00:13:07", updated_at: "2013-09-24 00:13:07">
irb(main):015:0> u.primary_billing_address = a
=> #<Address id: 3, created_at: "2013-09-24 00:13:07", updated_at: "2013-09-24 00:13:07">
irb(main):016:0> u.save!
=> true
irb(main):017:0> u.user_address
=> #<UserAddress id: 2, user_id: 3, address_id: 3, purpose: nil, created_at: "2013-09-24 00:13:18", updated_at: "2013-09-24 00:13:18">
(not what I want... purpose should be "billing")
我怎样才能做到这一点,以便它适用于新的和持久的记录?我已经提出了 90% 的解决方案,但是由于我的方法没有捕捉到的边缘情况而打破了一些随机规范。
要解决的最棘手的部分是association=
行为方式:在新记录上,它将关联排队以通过连接模型进行分配。
PS:我省略了has_one
用于获取我想要的地址的关系的条件。我认为这个问题与此无关。