Ruby on rails 多模型链接在MongoDB中实现数据库
我有员工模型,其中我有许多控制器 像 它们都与员工控制员有关。 我使用MongoDb,因为我有不同的控制器,我也有不同的型号。 在我的仪表板中,我必须显示相关的员工详细信息。其中一个字段来自contacts controller,另一个来自dependents_controller,另一个来自personal controller。 在这里,我必须调用所有模型,并从每个模型中获取一个字段。 我可以通过显示一个相关模型中的每个字段来自定义此代码吗。 我正在使用这个装置。我不能存储每个用户相关数据的id并通过用户模型调用吗? 我搞砸了。。如果是,那怎么办? 在我的员工控制器中Ruby on rails 多模型链接在MongoDB中实现数据库,ruby-on-rails,ruby,ruby-on-rails-3,mongodb,mongoid,Ruby On Rails,Ruby,Ruby On Rails 3,Mongodb,Mongoid,我有员工模型,其中我有许多控制器 像 它们都与员工控制员有关。 我使用MongoDb,因为我有不同的控制器,我也有不同的型号。 在我的仪表板中,我必须显示相关的员工详细信息。其中一个字段来自contacts controller,另一个来自dependents_controller,另一个来自personal controller。 在这里,我必须调用所有模型,并从每个模型中获取一个字段。 我可以通过显示一个相关模型中的每个字段来自定义此代码吗。 我正在使用这个装置。我不能存储每个用户相关数据的
def index
@employees = Employee.all
Employee.includes(:dependants).each do |dependant|
p dependant.firstname #example of pulling data for that related entity
end
end
另外,我如何定位到相关人员数据???查看mongoid文档的这一部分: 它应该能很好地说明如何在模型中实现关系逻辑 但是,我强烈建议您先阅读以下内容: 特别是引用和原子性部分 在过去,我被发现没有完全理解mongo和事务数据库引擎(如innodb)之间的区别,这导致我在项目中途重新设计了模型 应要求作出澄清 您可以像我的第一个链接所描述的那样设置您的模型:
class Employee
include Mongoid::Document
field :address, type: String
field :work, type: String
has_many :dependants
end
class Dependant
include Mongoid::Document
field :firstname, type: String
field :lastname, type: String
belongs_to :employee
end
在控制器中,您可以通过员工访问受抚养人数据:
#this example loops through every employee in the collection
Employee.includes(:dependants).each do |employee|
employee.dependants.each do |dependant|
p dependant.firstname #example of pulling data for that related entity
end
end
你能给我一些与我的控制器相关的编码示例吗?如果是这样的话,那我就要抓住我的答案了。我试过了。。但我没有明白。假设我有两个字段用于employee字段:address,type:String字段:work,type:String,两个字段用于dependent字段:firstname,type:String字段:lastname,type:String,那么我如何在模型和employee控制器中实现它呢。你能编辑代码吗。Thanksmy employee的索引控制器类似于def index@employees=employee.all employee.includes:dependents.each do | dependent | p dependent.firstname为相关实体end respond|u to do | format | format.html index.html.erb format.json{render json:@employees}end end它为@regmiprem提供了错误的未定义方法“firstname”,请参阅我上次的编辑,此代码看起来像我编辑问题时的上一版本,但我为名为prem的相关员工获得了错误的未定义方法“firstname”,我如何获取其依赖值。由于我有两个控制者,我如何将它们关联为我的员工控制者中的同一个人价值观。
#this example loops through every employee in the collection
Employee.includes(:dependants).each do |employee|
employee.dependants.each do |dependant|
p dependant.firstname #example of pulling data for that related entity
end
end