我有一个简单的用户模型
class User < ActiveRecord::Base
has_one :user_profile
end
还有一个简单的 user_profile 模型
class UserProfile < ActiveRecord::Base
belongs_to :user
end
问题是当我调用下面的构建方法时,没有调用保存方法,我最终在数据库中得到了一条新记录(如果它通过了验证)
class UserProfilesController < ApplicationController
def create
@current_user = login_from_session
@user_profile = current_user.build_user_profile(params[:user_profile])
#@user_profile.save (even with this line commented out, it still save a new db record)
redirect_to new_user_profile_path
end
任何人都知道发生了什么事。
这个方法的定义如下,但它仍然为我保存
build_association(attributes = {})
Returns a new object of the associated type that has been instantiated with attributes and linked to this object through a foreign key, but has not yet been saved.
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_one
最佳答案
好吧,我敢肯定经验丰富的 vert 已经知道这一点,但作为一个菜鸟,我必须从很长的路要走......让我看看我是否可以在不搞砸的情况下解释这一点
虽然我没有直接保存 user_profile 对象,但我注意到在我的日志中,每次我提交表单时都会更新用户模型的 last_activity_time(和 user_profile 模型)(当登录时,用户模型的 last_activity 日期也会更新在用户中也做了其他各种事情 - 我后来意识到这是在 Sorcery gem 配置中设置的)。
根据 http://api.rubyonrails.org/classes/ActiveRecord/AutosaveAssociation.html AutosaveAssociation 是一个模块,负责在保存父记录时自动保存关联记录。在我的例子中,用户模式是父级,他们在下面提供的场景反射(reflect)了我的经验。
class Post
has_one :author, :autosave => true
end
post = Post.find(1)
post.title # => "The current global position of migrating ducks"
post.author.name # => "alloy"
post.title = "On the migration of ducks"
post.author.name = "Eloy Duran"
post.save
post.reload
post.title # => "On the migration of ducks"
post.author.name # => "Eloy Duran"
以下解决方案解决了我的问题 1. 停止 Sorcery(配置设置)更新用户 last_activity_time(对于每个操作) 或者 2. 当我在用户模型中设置关联时传递一个':autosave => false'选项,如下所示
class User < ActiveRecord::Base
has_one :user_profile, :autosave => false
end
关于ruby - Rails 事件记录 : Calling Build Method Should Not Save To Database Before Calling Save Method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8071357/