加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – Rails Active Record:在调用Save方法之前,调用构建方法

发布时间:2020-12-17 02:53:19 所属栏目:百科 来源:网络整理
导读:我有一个简单的用户模型 class User ActiveRecord::Base has_one :user_profileend 还有一个简单的user_profile模型 class UserProfile ActiveRecord::Base belongs_to :userend 问题是当我调用以下构建方法而不调用save方法时,我最终得到了数据库中的新记录
我有一个简单的用户模型

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

解决方法

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

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

每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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读