【问题标题】:Implement of database in MongoDB by linking many models通过链接多个模型在MongoDB中实现数据库
【发布时间】:2012-12-24 10:54:10
【问题描述】:

我有员工模型,我有很多控制器 喜欢

jobs_controller.rb
contacts_controller.rb
personals_controller.rb
dependets_controller.rb

它们都与 Employee 控制器有关。 我正在使用 MongoDb,因为我有不同的控制器,我也有不同的型号。 在我的仪表板中,我必须显示相关的员工详细信息。其中一个字段来自联系人控制器,另一个来自dependents_controller,另一个来自个人控制器。 在这里,我必须调用所有模型并从每个模型中获取一个字段。 我可以通过显示来自一个相关模型的每个字段来自定义此代码吗? 我正在使用设计。我不能存储每个用户相关数据的 id 并通过用户模型调用吗? 我搞砸了..如果是,那怎么办? 在我的员工控制器中

def index
    @employees = Employee.all
    Employee.includes(:dependants).each do |dependant|
     p dependant.firstname #example of pulling data for that related entity
     end


  end

还有我如何定位到相关人员数据??

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 mongodb mongoid


    【解决方案1】:

    查看 mongoid 文档的这一部分:http://mongoid.org/en/mongoid/docs/relations.html 它应该可以很好地说明如何在模型中实现关系逻辑。

    但是,我强烈建议您先阅读以下内容: http://docs.mongodb.org/manual/core/data-modeling

    尤其是引用和原子性部分。

    过去我发现没有完全理解 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
    

    【讨论】:

    • 你能给我一些与我的控制器相关的编码示例吗?如果是这样,那么我会很快抓住我的答​​案
    • 我试过了..但我没有得到它。假设我有 2 个字段用于员工字段:地址,类型:字符串字段:工作,类型:字符串和两个字段用于依赖字段:名字,类型:字符串字段:姓氏,类型:字符串那么我如何在模型中实现它以及在员工控制器中。你可以编辑代码。谢谢
    • 我的员工索引控制器是这样的 def index @employees = Employee.all Employee.includes(:dependants).each do |dependant| pdependant.firstname #为该相关实体提取数据的示例 end respond_to do |format| format.html # index.html.erb format.json { render json: @employees } end end 它给出了错误 undefined method `firstname' for #<0x0000000201a2f0>
    • <0x00000001eff6e0>
    猜你喜欢
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 2012-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多