Rails中的多级关联?

时间:2012-11-25 03:25:49

标签: ruby-on-rails ruby

我正在开展医疗申请。在其中,我有用户和客户之间的关联(显然),用户和治疗之间的关联,用户和设置(用于设置表)。

但这里棘手的部分是客户也必须与治疗表相关联,因为他们是那些在他们的记录上有治疗的人。用户只是管理上述所有内容的用户。此外,我们还有与客户相关的患者,因此需要多层次。所以业主有客户也有病人。患者和客户一样都有治疗方法。

对我而言似乎非常复杂,我很难获得超出用户工作的任何东西。我正在使用Rails中的基本关系设置(我对rails很少了解)。我在create方法上使用@ treatment.user = current_user,然后简单地将所需的表与user_id相关联。我在治疗台上放了一个client_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 :email, :password, :password_confirmation,
                :remember_me, :role

  validates :email, presence: true
  has_many :clients
  has_many :settings
  has_many :treatments

  ROLES = %w[admin receptionist practitioner]

  def role_symbols
    [role.to_sym]
  end

  def to_s
    email
  end

end

1 个答案:

答案 0 :(得分:2)

我还不完全确定你的问题是什么。 但既然你提到你不熟悉Rails,这可能会对你有所帮助:

查看has_many :through relation(也可用has_one :through

所以你可能会做这样的事情:

# patient.rb
class Patient < ActiveRecord::Base
  has_many :treatments, :through => :client
end