Rails Active Record:在调用Save方法之前,调用构建方法不应保存到数据库

时间:2011-11-09 20:40:06

标签: ruby ruby-on-rails-3 activerecord

我有一个简单的用户模型

class User < ActiveRecord::Base
    has_one :user_profile
end

一个简单的user_profile模型

class UserProfile < ActiveRecord::Base
    belongs_to :user
end

问题是当我调用以下构建方法而不调用save方法时,我最终在数据库中找到了一条新记录(如果它通过了验证)

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

Anyyyyyy有任何想法发生了什么。

此方法的定义如下所示,但它仍然为我节省了

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

1 个答案:

答案 0 :(得分:8)

好吧,我确信经验丰富的兽医已经知道了这一点,但作为一个新手,我不得不弄清楚这一点......让我看看我是否可以在不搞砸的情况下解释这一点

虽然我没有直接保存user_profile对象,但我在日志中注意到每次提交表单时都会更新用户模型的last_activity_time(以及user_profile模型)(用户模型的last_activity日期也会在记录时更新)在用户中也做了各种其他事情 - 后来我意识到这是在Sorcery gem配置中设置的。)

http://api.rubyonrails.org/classes/ActiveRecord/AutosaveAssociation.html AutosaveAssociation是一个模块,负责在保存父项时自动保存相关记录。在我的例子中,用户模式是父模式,他们在下面提供的场景反映了我的经验。

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.停止巫术(配置设置)以更新用户last_activity_time(针对每个操作) 要么 2.传递':autosave =&gt;我在用户模型中设置关联时的false'选项如下

class User < ActiveRecord::Base
    has_one :user_profile, :autosave => false
end
相关问题