【发布时间】:2014-05-04 08:53:21
【问题描述】:
如何在单个操作中保存不同的表值???
我想在用户创建操作中保存 User 和 Email 表值。
在模型中
class User
include Mongoid::Document
field :name, :type => String
field :email_id, :type => Integer
field :active, :type => Boolean
field :status_id, :type => Integer
has_one :email
has_one :status
validates :name, :status_id, :active, :presence => true
validates :email_id, uniqueness: true
end
class Email
include Mongoid::Document
field :email_id, :type => String
field :type, :type => String
field :status_id, :type => Integer
field :old, :type => Boolean
field :active, :type => Boolean
field :version, :type => Integer
has_one :status
validates :email_id, :type, :version, :status_id, :active, :presence => true
end
class Status
include Mongoid::Document
field :name, :type => String
field :status_type, :type => String
field :created_at, :type => DateTime
field :updated_at, :type => DateTime
end
在控制器中
def user_create
@user = User.new(user_params)
status_id = status.where(:name => "Published").first
email = Email.new(:email_id => params[:email_id], :type => "User_Email", :version => 1, :active => true, :status_id => status_id.id)
email.save
@user.active = true
@user.status_id = status_id.id
@user.email_id = email.id
if @user.save
redirect_to action: :list
else
redirect_to action: :new_user
end
end
def user_params
params.require(:user).permit(:name, :alt_name )
end
在调试控制台中
email.id => {BSON::ObjectId} 5365f53f63686511fb010000
用户电子邮件始终为零
@user.email_id = email.id => 0
所以我无法保存用户 ID,因为用户电子邮件 ID 总是为零
我尝试将 BSON id 转换为正常 id,当时它也没有使用
email.id.to_s => "5365f53f63686511fb010000"
只有在我使用 mongoid 时如何获取 id ???
我必须保存用户表值和电子邮件表值。
我正在使用
ruby 2.0.0p353
Rails 4.0.2
gem 'bson_ext'
gem 'mongo'
gem 'mongoid', github: 'mongoid/mongoid'
我必须自动更新电子邮件表格版本。每次用户表更新我都想自动更新电子邮件表版本。
如何在邮件表中自动维护版本更新??
如何解决这个问题???
【问题讨论】:
-
看
accepts_nested_attributes这是通过关联同时保存多个模型的最简单方法。或者您可以在after_create或after_update上为User设置回调 -
嗨 ngineersmnky,我不知道如何使用这个?你能举一些例子吗?
标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2