首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模型关联Rails 4

模型关联Rails 4
EN

Stack Overflow用户
提问于 2014-07-01 09:11:12
回答 1查看 56关注 0票数 0

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

现在我有了以下模型

用户模型

代码语言:javascript
复制
class User < ActiveRecord::Base
  has_many :people, :dependent => :destroy 
    devise :database_authenticatable, :confirmable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

人模型

代码语言:javascript
复制
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-z\d\-.]+\.[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?

谢谢!

请将用户视为支持者,将个人视为受抚养人--这就是我所想的,如下所示:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-01 09:27:14

has_many :through关联应该在这种情况下工作。

我对UserPerson之间的区别还不十分清楚,所以我将暂时获得一些许可,并处理Person模型,但是您可以很容易地接受这个想法,并将其应用于User

连接模型可能类似于,

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24506488

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档