【发布时间】:2016-03-15 19:33:18
【问题描述】:
我有一个多态地址表,
create_table :addresses do |t|
t.integer :address_type, default: 0, null: false
t.string :addressable_type
t.integer :addressable_id
t.belongs_to :city
t.belongs_to :state
t.belongs_to :country
t.string :address_line_1
t.string :address_line_2
t.string :address_line_3
t.integer :pin_code, limit: 6
t.datetime :deleted_at
t.timestamps null: false
end
保持address_type 分配本地永久地址的想法如下:
enum address_type: {default: 0, local: 1, permanent: 2, residential: 3, office: 4}
问题是,我如何定义关联来定义:
class User < ActiveRecord::Base
has_one :local_address
end
我尝试了很多选项,例如:
has_many :addresses, as: :addressable
has_one :present_address, -> { where address_type: :local }, through: :addresses, source: :addressable
has_one :present_address, -> { addresses.where(address_type: :local) }
或
has_one :present_address, through: :addresses, conditions: { address_type: :local }, source: :addressable
has_one :permanent_address, through: :addresses, conditions: { address_type: :permanent }, source: :addressable
但无济于事。我们应该如何定义这种关联?
提前致谢。
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 associations polymorphic-associations