【问题标题】:Rails Active Record: Calling Build Method Should Not Save To Database Before Calling Save MethodRails Active Record:调用构建方法不应在调用保存方法之前保存到数据库
【发布时间】:2011-11-09 20:40:06
【问题描述】:

我有一个简单的用户模型

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

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

【问题讨论】:

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


    【解决方案1】:

    好的,我相信经验丰富的兽医已经知道这一点,但作为一个菜鸟,我必须弄清楚这一点......让我看看我是否可以在不搞砸的情况下解释这一点

    虽然我没有直接保存 user_profile 对象,但我注意到在我的日志中,每次提交表单时都会更新用户模型的 last_activity_time(和 user_profile 模型)(用户模型的 last_activity 日期也在登录时更新in user 也做了很多其他的事情——我后来意识到这是在 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 => false'选项,如下所示

    class User < ActiveRecord::Base
        has_one :user_profile, :autosave => false
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-22
      • 1970-01-01
      • 2020-06-09
      • 2020-07-03
      • 1970-01-01
      • 2015-05-09
      • 2020-08-02
      • 2011-10-08
      相关资源
      最近更新 更多