ruby – Rails Active Record:在调用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 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" 以下决议解决了我的问题 class User < ActiveRecord::Base has_one :user_profile,:autosave => false end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |