Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby Rails活动记录:调用生成方法不应在调用保存方法之前保存到数据库_Ruby_Ruby On Rails 3_Activerecord - Fatal编程技术网

Ruby Rails活动记录:调用生成方法不应在调用保存方法之前保存到数据库

Ruby Rails活动记录:调用生成方法不应在调用保存方法之前保存到数据库,ruby,ruby-on-rails-3,activerecord,Ruby,Ruby On Rails 3,Activerecord,我有一个简单的用户模型 class User < ActiveRecord::Base has_one :user_profile end 好的,我相信经验丰富的兽医已经知道这一点,但作为一名新手,我必须在漫长的道路上找到答案……让我看看我是否可以解释这一点,而不会把事情搞砸 虽然我没有直接保存user_profile对象,但我在日志中注意到,每次提交表单时,都有东西在更新用户模型的最后一次_活动时间(以及用户_profile模型)(当登录用户还做了其他各种事情时,用户模型的最后

我有一个简单的用户模型

class User < ActiveRecord::Base
    has_one :user_profile
end

好的,我相信经验丰富的兽医已经知道这一点,但作为一名新手,我必须在漫长的道路上找到答案……让我看看我是否可以解释这一点,而不会把事情搞砸

虽然我没有直接保存user_profile对象,但我在日志中注意到,每次提交表单时,都有东西在更新用户模型的最后一次_活动时间(以及用户_profile模型)(当登录用户还做了其他各种事情时,用户模型的最后一个_活动日期也被更新了——我后来意识到这是在巫术宝石配置中设置的)

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.停止巫术(配置设置)更新用户上次的活动时间(对于每个动作) 或 2.在用户模型中设置关联时,传递一个“:autosave=>false”选项,如下所示

class User < ActiveRecord::Base
    has_one :user_profile, :autosave => false
end
class用户false
结束
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.
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