【问题标题】:Nested attributes in mongodb confusionmongodb混淆中的嵌套属性
【发布时间】:2012-10-01 06:53:36
【问题描述】:

我正在使用带有数据库 Mongodb 的 Rails。 我正在使用设计。设计有模型名称用户。用户的 id 在

:id => current_user.id

我想制作一个模型,当从表单保存数据时,当前用户的 id 也会保存在集合中。 我的员工的型号是

 class Employee
  include Mongoid::Document
  field :first_name, type: String
  field :middle_name, type: String
  field :last_name, type: String
  field :otherid, type: String
  field :licennum, type: String
  field :citizennum, type: String
  field :licenexp, type: String
  field :gender, type: String
   field :state, type: String
  field :marital_status, type: String
  field :country, type: String
  field :birthdate, type: String
  field :nickname, type: String
  field :description, type: String
  validates_presence_of :first_name

{ }

end

我应该在大括号内放什么,这样当从该模型保存数据时,它也会在其中保存当前用户 ID?

【问题讨论】:

    标签: ruby-on-rails mongodb devise mongoid


    【解决方案1】:

    您显示的代码仅包含个人信息字段,例如出生日期等。我想最简单的解决方案是将它们放在User 类中,并使用诸如devise/registrations#edit 之类的内置设计操作更改它们,默认情况下将更改应用于current_user

    或者,如果您想将 Employee 保留为一个单独的类,您可以尝试将 Employee 嵌入到 User 类中,如下所示:

    class User 
      include Mongoid::Document
    
      embeds_one :employee
      (...)
    
    class Employee
      include Mongoid::Document
    
      embedded_in :user
    

    在这种情况下,您将在控制器级别设置关系,例如:

    class EmployeesController < ApplicationController
    
      def create
        current_user.create_employee(params[:employee])
      end
    

    创建后,您可以从 Employee 类中以user.id 访问用户 ID。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-21
      • 2014-05-30
      • 1970-01-01
      • 2019-12-29
      • 2011-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多