Ruby on rails mongodb中的嵌套属性
我将rails与数据库Mongodb一起使用。 我正在使用这个装置。Deviate具有模型名user。用户的id位于中Ruby on rails mongodb中的嵌套属性,ruby-on-rails,mongodb,devise,mongoid,Ruby On Rails,Mongodb,Devise,Mongoid,我将rails与数据库Mongodb一起使用。 我正在使用这个装置。Deviate具有模型名user。用户的id位于中 :id => current_user.id 我想建立一个模型,这样当从表单保存数据时,当前用户的id也会保存在集合中。 我的员工的模型是 class Employee include Mongoid::Document field :first_name, type: String field :middle_name, type: String f
: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
{
}
我应该在花括号内放些什么,这样当从该模型保存数据时,它也会在其中保存当前用户id?您显示的代码只包含诸如出生日期之类的个人信息字段。我认为最简单的解决方案是将它们放在
User
类中,并使用内置的设计操作(如design/registrations#edit
)对它们进行更改,默认情况下将更改应用于当前用户
或者,如果希望将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
class EmployeesController
创建后,您可以从Employee类中访问用户ID作为user.ID
class EmployeesController < ApplicationController
def create
current_user.create_employee(params[:employee])
end