【问题标题】:1 user model with student,tutor role + different profile for student, tutor?1 个具有学生、导师角色的用户模型 + 学生、导师的不同个人资料?
【发布时间】:2013-11-30 12:25:08
【问题描述】:

如何正确设置具有 2 个角色的用户模型,并为每个角色设置 2 个单独的配置文件模型?我对如何实施感到困惑。目前我正在使用它,但它失败了:

models/user.rb

  #  id                     :integer ( only important columns noted to save space)
  #  profile_id             :integer
  #  profile_type           :string(255) 

  belongs_to :profile, :polymorphic => true

models/profile_student.rb:

  #  user_id     :integer      
  has_one :user, as: :profile, dependent: :destroy

models/profile_tutor.rb:

  #  user_id     :integer   
  has_one :user, as: :profile, dependent: :destroy

如何正确获取用户的个人资料? 例如使用设计。

@user = current_user.profile

【问题讨论】:

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


    【解决方案1】:

    我会尝试拥有两种类型的用户:学生和导师。为了做到这一点,在你的用户表中,有一个名为 type 的列,并进行验证,以确保它是学生或导师:

    validates :type, :inclusion => {:in => ['student', 'tutor']}
    

    然后创建一个 Student 模型和一个 Tutor 模型。在 rails 中,'type' 是一种特殊的属性,rails 会知道它指的是其他模型。然后,为了制作配置文件,您有两个选择。您可以说学生和导师都拥有一个 :profile,也可以将个人资料的类型分开。

    例如,你可以这样做:

    class Student < User
        has_one :profile
    end
    
    class Tutor < User
        has_one :profile
    end
    

    如果两个个人资料的信息类型相似,那可能对您有用。但是,如果导师和学生的个人资料有很大不同,请尝试以下操作:

    class Student < User
        has_one :student_profile
    end
    
    class Tutor < User
        has_one :tutor_profile
    end
    

    然后为每种类型的配置文件创建一个单独的模型。

    通过使用此“类型”列,您可以让学生和导师继承用户的所有方法和属性,但也可以拥有自己独特的属性和方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多