模型关联Rails 4



在开始编码之前我想知道你的意见。

现在我有以下模型

用户模型

class User < ActiveRecord::Base
  has_many :people, :dependent => :destroy 
    devise :database_authenticatable, :confirmable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end
<<p> 人模型/strong>
class Person < ActiveRecord::Base
    belongs_to :user
    has_many :diseases, :dependent => :destroy #if you delete a person you also delete all diseases related
    has_many :appointments, :dependent => :destroy
    validates_presence_of :name, :email
    validates :name, :length => {:maximum => 50, :too_long => "name is too long"}
    VALID_EMAIL_REGEX = /A[w+-.]+@[a-zd-.]+.[a-z]+z/i
    validates :email, format: { :with => VALID_EMAIL_REGEX , message: "is invalid" }
    accepts_nested_attributes_for :diseases, :reject_if => proc { |attributes| attributes['name'].blank? }
end

它必须像这样工作:

一个用户可以有n个依赖的人(儿童,残疾人等),但同时这个人应该能够有自己的用户和依赖的人。

还有什么建议?我应该在用户和人之间使用has_many_and_belongs_to模型吗?

谢谢!


请将用户视为支持者,将个人视为受抚养人我想的是这样的:

class Relationship
  belongs_to :user
  belongs_to :person
end
class User
  has_many :relationships
  has_many :people, through: :relationships
end
class Person
  has_many :relationships
  has_many_and_belong_to :users, through: :relationships
end

在这种情况下,has_many :through协会应该起作用。

我不是100%清楚UserPerson之间的差异,所以我要采取一点许可,暂时处理Person模型,但你可以很容易地接受这个想法,并将其应用于User

连接模型可以是这样的,

class Relationship
  belongs_to :dependant, class_name: 'Person'
  belongs_to :supporter, class_name: 'Person'
end
class User
  ...
  has_many :relationships
  has_many :dependants, through: :relationships
  has_many :supporters, through: :relationships
end

最新更新