我有一个用户和帐户模型,其中包含 has_one 关联和嵌套属性。
我的问题是,当通过Devise注册用户时,不会创建帐户,也不会在日志中生成错误。
我正在使用Rails 3.2和Devise 2.0.4。
user.rb
class User
include Mongoid::Document
has_one :account, :inverse_of => :user
accepts_nested_attributes_for :account
field :name
validates_presence_of :name
validates_uniqueness_of :name, :email, :case_sensitive => false
attr_accessible :name, :email, :password, :password_confirmation, :remember_me, :account_attributes
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
...
end
account.rb
class Account
include Mongoid::Document
belongs_to :user, :inverse_of => :account
field :name
validates_presence_of :user
attr_accessible :name, :user_id
end
registration_controller.rb
class RegistrationsController < Devise::RegistrationsController
def new
resource = build_resource({})
resource.build_account
respond_with resource
end
end
查看
<h2>Sign up</h2>
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<%= f.fields_for :account do |account_form| %>
<div><%= account_form.label 'Company' %>
<%= account_form.text_field :name %></div>
<% end %>
...
这是我的控制台输出
Started POST "/users" for 127.0.0.1 at 2012-03-21 03:40:55 -0700
Processing by RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"dAmJrthe/IjlHzjBI2kF9nkTxwIWM0o69Q1PI2nd95o=", "user"=>{"account_attributes"=>{"name"=>"comp11"}, "name"=>"user11", "email"=>"uu3@u3.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
MONGODB (1ms) myapp_development['$cmd'].find({"count"=>"users", "query"=>{:email=>"uu3@u3.com"}, "fields"=>nil}).limit(-1)
MONGODB (0ms) myapp_development['$cmd'].find({"count"=>"users", "query"=>{:name=>/^user11$/i}, "fields"=>nil}).limit(-1)
MONGODB (0ms) myapp_development['$cmd'].find({"count"=>"users", "query"=>{:email=>/^uu3@u3\.com$/i}, "fields"=>nil}).limit(-1)
MONGODB (1ms) myapp_development['users'].insert([{"email"=>"uu3@u3.com", "encrypted_password"=>"$2a$10$lY6aHKTyeVALAcIkX.Ipke5YMj7/viU9Hy5s.jsQAq7cfCBtJtXaO", "sign_in_count"=>0, "_id"=>BSON::ObjectId('4f69b0377e3d3639bf000008'), "name"=>"user11"}])
MONGODB (0ms) myapp_development['users'].update({"_id"=>BSON::ObjectId('4f69b0377e3d3639bf000008')}, {"$set"=>{"last_sign_in_at"=>2012-03-21 10:40:56 UTC, "current_sign_in_at"=>2012-03-21 10:40:56 UTC, "last_sign_in_ip"=>"127.0.0.1", "current_sign_in_ip"=>"127.0.0.1", "sign_in_count"=>1}})
Redirected to http://localhost:3000/
Completed 302 Found in 257ms
如您所见,我看不到有关创建帐户的任何信息。还验证了通过查看MongoDB没有创建帐户集合。我错过了什么? 提前感谢您的帮助。
答案 0 :(得分:2)
解决了这个问题 我需要打开:自动保存
has_one :account, :inverse_of => :user, :autosave => true
mongoid docs指出了这个问题。
请注意:如果您不想在更新时手动保存关系,则需要为neighbor_nested_attributes_for使用的关系关联启用:autosave选项。