与多态表的一对多条件关联:Rails

时间:2016-03-15 19:33:19

标签: ruby-on-rails ruby-on-rails-4 associations polymorphic-associations

我有一个多态地址表,

   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) }

OR

has_one :present_address, through: :addresses, conditions: { address_type: :local }, source: :addressable
has_one :permanent_address, through: :addresses, conditions: { address_type: :permanent }, source: :addressable

但无济于事。我们该如何定义这种关联呢?

提前致谢。

1 个答案:

答案 0 :(得分:0)

对于Rails还是新手,如果我错误或错误,请纠正我。希望我能正确理解你的要求。

我认为,当您希望模型一次具有多个模型的belongs_to关联时,多态关联非常有用。在您的情况下,似乎您将地址模型与仅一个模型关联,即用户模型。

让我们考虑没有多态关联的地址模型,以及以下字段。 user_id,address_type,city,state,country,address_line_1,address_line_2,address_line_3,pin_code,deleted_at

请注意user_id字段,以便将地址与用户相关联。这将需要您的地址模型包括

belongs_to :user

现在您可以使用以下用户模型:

has_many :addresses
has_one :local_address, -> { where address_type: "local" }, class_name: "Address"

为permanent_address,residential_address等添加类似的代码行。

在这种情况下,地址模型中address_type字段的可能值将是&#34; local&#34;,&#34; permanent&#34;,&#34; residential&#34;,&#34; office& #34;等

希望这有帮助。