Rails设计多态

时间:2013-02-07 00:44:47

标签: ruby-on-rails devise polymorphic-associations

我正在使用设计,我希望创建一个多态关系,我将列添加到表用户'userable_type'和'usersable_id'

这是我的代码

型号>>用户

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  # attr_accessible :title, :body
  attr_accessible :email, :password, :password_confirmation, :remember_me

  #usarsable
  belongs_to :usersable, :polymorphic => true, :autosave => true, :dependent => :destroy
  accepts_nested_attributes_for :usersable

end

型号&gt;&gt;医师

class Medic < ActiveRecord::Base
  attr_accessible :license_number, :specialty

  has_one :user, as: :usersable, dependent: :destroy
  has_and_belongs_to_many :patients
end

型号&gt;&gt;患者

class Patient < ActiveRecord::Base
  belongs_to :socialsecurity
  attr_accessible :birthday, :blood_type
  has_one :user, as: :usersable, dependent: :destroy
  has_many :contacts
  has_and_belongs_to_many :medics
end

覆盖设计控制器

class RegistrationsController < Devise::RegistrationsController
  def new
    super
    @user.build_usersable # I had problem in this line
  end

  def create
  end

  def update
    super
  end
end 

这些是我目前拥有的所有模型,但我仍然遇到同样的问题,我不知道如何创建和保存多态对象。

错误仍然相同

  

错误:“&lt; #User:”的未定义方法`build_usersable'

有人可以帮助我,我会很感激

提前致意并表示感谢

巨力。

1 个答案:

答案 0 :(得分:0)

根据评论中的对话,这是我认为你需要的那种方案。

我将使用Aspect的概念,即用户可以有很多方面,方面可能是军医,内容细节等;一个Aspect只能有一个用户。

首先,您需要一个UserAspect模型,该模型具有user_id和aspect_type以及aspect_id

class UserAspect < ActiveRecord::Base

  belongs_to :user
  belongs_to :aspect, :polymorphic => true
end

现在是您的用户模型

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  # attr_accessible :title, :body
  attr_accessible :email, :password, :password_confirmation, :remember_me

  #aspects
  has_many :user_aspects
  has_many :aspects, :through => :user_aspects

end

现在你的医生

class Medic < ActiveRecord::Base
  attr_accessible :license_number, :specialty

  has_one :user_aspect, as: :aspect, dependent: :destroy
  has_one :user, :through => :user_aspect
end

现在你可以做像

这样的事情
user.aspects

medic.user

etc