Tim Santeford
Tim Santeford

Reputation: 28151

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

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

Upvotes: 3

Views: 1950

Answers (2)

Simone Carletti
Simone Carletti

Reputation: 176552

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.

Upvotes: 5

gicappa
gicappa

Reputation: 4882

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

Upvotes: 1

Related Questions