ActiveRecord多态模型关联混淆

时间:2015-02-10 02:09:31

标签: ruby-on-rails-4 rails-activerecord polymorphic-associations rails-migrations model-associations

我有一个rails 4应用程序,我已经设置了一个用户模型。我希望用户与用户个人资料模型建立 has_many 关联,但这里有一个问题:

  1. 我的用户个人资料模型需要polymorphic - 用户模型可以关联多个(不同的)用户配置文件 用它(例如ProfileTypeA,ProfileTypeB,ProfileTypeC等)
  2. 我希望我的用户模型有一个关联,比如user_profiles 将返回与其关联的所有用户的用户配置文件。
  3. 我相信我是在正确的轨道上(或者我?),但是如何使用轨道发生器实现这一目标?对我来说最让人困惑的部分是如何做上面的子弹#2。

    P.S。我看了一下STI,但在我看来,我的用户模型必须与每个用户配置文件类型模型有一个硬关联,我不喜欢它,因为它会改变用户模型我添加到数据模型中的每个新用户配置文件类型。

1 个答案:

答案 0 :(得分:1)

你发声正确,请尝试以下

#The polymorphic models
class User
  has_many :user_profiles, as: :profileable
end

class UserProfile
 belongs_to :profileable, polymorphic: true
end

下面的迁移

#migrations
class CreateUserProfiles < ActiveRecord::Migration
  def change
    create_table :user_profiles do |t|
      t.integer :profileable_id
      t.string  :profileable_type
      t.timestamps null: false
    end

    add_index :user_profiles, :profileable_id
  end
end
相关问题