Why do my changes to model instances not get saved sometimes in Rails 3?

爱⌒轻易说出口 提交于 2020-01-02 08:55:10

问题


I have a model named Post and I created two methods within the model that make changes to fields. The first method's changes get persisted when a save is called. The second method's changes do not get saved. I have noticed this behavior before in other models and I think I'm missing some basic knowledge on how models work. Any help on this would be greatly appreciated!

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  

EDIT:

Here is a snippet from the 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

  ...

UPDATE Problem was solved by adding self to all the attributes being changed in the model. Thanks Simone Carletti


回答1:


In publish you call the method touch that saves the changes to the database. In unpublish, you don't save anything to the database.

If you want to update a model, be sure to use a method that saves the changes to the database.

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

Also, make sure to use self.attribute when you set a value, otherwise the attribute will be consideres as a local variable.




回答2:


In my experience you don't persist your changes until you save them so you can

  • explicitly call Model.save in your controller
  • explicitly call Model.update_attributes(params[:model_attr]) in your controller
  • if you want to save an attribute in your model I saw something like write_attribute :attr_name, value but TBH I never used it.

Cheers



来源:https://stackoverflow.com/questions/4848686/why-do-my-changes-to-model-instances-not-get-saved-sometimes-in-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!