【问题标题】:ActiveRecord polymorpic model association confusionActiveRecord 多态模型关联混淆
【发布时间】:2015-02-10 02:09:30
【问题描述】:

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

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

我相信我在正确的轨道上(或者我是吗?),但是如何使用 rails 生成器来完成呢?最让我困惑的部分是如何执行上面的第 2 条。

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

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

    • AnkitG - 这似乎是我正在寻找的,但假设我有类 UserAProfile
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多