gpt4 book ai didi

ruby-on-rails - 为什么我对模型实例的更改有时不会在 Rails 3 中保存?

转载 作者:行者123 更新时间:2023-12-03 16:20:43 25 4
gpt4 key购买 nike

我有一个名为 Post 的模型,我在模型中创建了两个方法来更改字段。当调用保存时,第一个方法的更改会保留下来。第二种方法的更改不会被保存。我之前在其他模型中注意到过这种行为,我想我缺少一些关于模型如何工作的基本知识。如有任何帮助,我们将不胜感激!

class Post < ActiveRecord::Base

def publish(user) # These changes get saved
reviewed_by = user
touch(:reviewed_at)
active = true
end

def unpublish() # These changes get ignored.
reviewed_by = nil
reviewed_at = nil
active = false
end

end

编辑:

这是来自 Controller 的片段"

class PostsController < ApplicationController

def publish
if request.post?
post = Post.find(params[:id].to_i)
post.publish(current_user)
redirect_to(post, :notice => 'Post was successfully published.')
end
end

def unpublish
if request.post?
post = Post.find(params[:id].to_i)
post.unpublish()
redirect_to(post, :notice => 'Post was successfully unpublished.')
end
end

...

更新通过将 self 添加到模型中正在更改的所有属性来解决问题。谢谢Simone Carletti

最佳答案

publish 中调用方法touch将更改保存到数据库。在 unpublish 中,您不会将任何内容保存到数据库中。

如果要更新模型,请务必使用将更改保存到数据库的方法。

def publish(user)
self.reviewed_by = user
self.active = true
self.reviewed_at = Time.now
save!
end

def unpublish
self.reviewed_by = nil
self.reviewed_at = nil
self.active = false
save!
end

此外,请确保在设置值时使用 self.attribute,否则该属性将被视为局部变量。

关于ruby-on-rails - 为什么我对模型实例的更改有时不会在 Rails 3 中保存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4848686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com