如何在Rails中实现这种结构?
User
has_one :health
Health
belongs_to :user
has_many :weights
has_many :diseases
Health::Weight
belongs_to :health
Health::Diseases
belongs_to :health
users
health_id:integer
healths
id:integer
health_weights
current:integer
health_id:integer
health_diseases
name:text
health_id:integer
当我生成r g model Health::Weight current:integer
我的Health
是没有ActiveRecord的模块时:
module Health
def self.table_name_prefix
'health_'
end
end
我这个好方法吗?
据我了解,您要达到的目标是这样的:
给定用户的健康状况可以具有许多健康特征(体重,疾病等)。
您想将与健康特征相对应的模型放在模块中,以将它们与应用程序的其他部分明确分开
实际上,这与使用Health :: Weight和Health :: Diseases一样使用“健康”模块是一个好案例。
但是,您不应使用称为“健康”的模型作为将用户链接到其健康特征的模型。
这首先导致语义上的混乱,但也无法在代码中工作:健康不能同时是ActiveRecord :: Base子类(或其他“ ORM类”)和封装其他表(如体重和疾病)的模块。
=>用更清晰的模型名称替换您的健康模型,该名称明确指出它是用户与其健康特征(体重,疾病等)之间的链接。例如UserHealthProfile。
最终结构将是:
class User
has_one :user_health_profile
end
class UserHealthProfile
belongs_to :user
has_one :weight
has_many :diseases
end
module Health
def self.table_name_prefix
'health_'
end
end
class Health::Weight
belongs_to :user_health_profile
end
class Health::Disease
belongs_to :user_health_profile
end
您也可以将UserHealthProfile模型放入Health模块中,如下所示:
class Health::UserHealthProfile
end
注意:将模型封装到模块中时,在定义关联时可能需要添加class_name参数,但这取决于您的实际模块结构。
例子:
# let's say UserHealthProfile doesn't belong to the Health module
class UserHealthProfile
belongs_to :user
has_one :weight, class_name: Health::Weight
has_many :diseases, class_name: Health::Disease
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句