0

我有一个rails 4应用程序,我已经设置了一个用户模型。我希望用户与用户配置文件模型的has_many联系,但这里的渔获:ActiveRecord polymorpic模型关联混淆

  1. 我的用户配置文件模型需要polymorphic - 在 用户模型可以有关联的多个(不同的)的用户配置文件(例如ProfileTypeA,ProfileTypeB,ProfileTypeC等)
  2. 我希望我的用户模型有一个关联,比如user_profiles, 将返回与其关联的所有用户的用户配置文件。

我相信我走在正确的轨道上(或者我?),但是如何使用轨道生成器来实现?对我来说最令人困惑的部分是如何做上面的第二项子弹。

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

回答

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 
+0

AnkitG - 这似乎正是我要找的,但假设我有 类UserAProfile < ActiveRecord :: Base has_many:user_profiles,as :: profileable end 如何将UserAProfile对象添加到User#user_profiles? 这是我的UserAProfile迁移: create_table“user_a_profiles”,force::cascade do | t | #将在以后添加更多字段... t.datetime“created_at”,null:false t.datetime“updated_at”,null:false end – gangelo 2015-02-10 13:58:27