【问题标题】:One to Many Conditional Association with Polymorphic table: Rails与多态表的一对多条件关联:Rails
【发布时间】: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


    【解决方案1】:

    对 Rails 还是新手,如果我弄错了,请纠正我。希望我正确理解了您的要求。

    我认为,当您希望模型一次与多个模型具有 belongs_to 关联时,多态关联很有用。在您的情况下,您似乎只将 Address 模型与一个模型相关联,即 User 模型。

    让我们考虑一下没有多态关联的地址模型,它具有以下字段。 user_id,address_type,城市,州,国家,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"
    

    为永久地址、住宅地址等添加类似的代码行。

    在这种情况下,Address 模型中 address_type 字段的可能值为“local”、“permanent”、“residential”、“office”等。

    希望这会有所帮助。

    【讨论】:

    • 我的address 表也与其他表相关联。但是我有一对一的关联(默认地址)没有任何问题。但是用户可以有多个地址,所以我粘贴了User table sn-p。 ActiveRecord::HasManyThroughSourceAssociationNotFoundError: Could not find the source association(s) "local_address" or :local_address in model Address. Try 'has_many :local_address, :through =&gt; :addresses, :source =&gt; &lt;name&gt;'. Is it one of versions, addressable, city, state, or country? from activerecord-4.2.5.1/lib/active_record/reflection.rb:850:in check_validity!'`
    • 尝试了所有这些选项,但没有奏效。此外,对于:through,我们需要一个中间表。所以我确定我在这里遗漏了任何东西。一种解决方法是删除 polymorphism 并将其作为一个简单的关联进行。
    • 我想我明白了。将has_one :permanent_address, through: :addresses, conditions: { address_type: :permanent }, source: :addressable 替换为has_one :permanent_address, -&gt; { where address_type: 2 }, as: :addressable, class_name: "Address"
    • 之前没用。但不知何故,今天它奏效了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    相关资源
    最近更新 更多