donald
donald

Reputation: 23737

Persistent variables in Rails 3

def edit
    @title ="Edit account"
    @page_name = "edit"    
  end

  def update
    if @wsp.update_attributes(params[:wsp])
      # it worked
      flash[:success] = "Profile updated."
      if (@title == "Location")
        redirect_to wsp_location_path
      else
        redirect_to edit_wsp_path
      end
    else 
      @title = "Edit account"
      render 'edit'
    end
  end

The variable @title is empty when in the update method. How can I make the @title persistent so I can read it?

Upvotes: 0

Views: 1533

Answers (3)

Ryan Bigg
Ryan Bigg

Reputation: 107728

If the entire purpose of this is to display it on the Edit page, why not put it there (app/views/the_controller/edit.html.erb)? That way it'd be shown on all requests to that page and you're not putting view / presentation code into the controller where it doesn't belong.

Upvotes: 0

Alex Wayne
Alex Wayne

Reputation: 187024

In the edit action, you should write the result to a form field, perhaps a hidden field. Then read that data back in from the submitted form in your update action. You really should not preserve any state server side between these 2 requests.

And while you could use the session, I would advise against this. Overuse of the session for passing tiny bits of short lived data between requests is generally bad form.

Upvotes: 0

Adam Lassek
Adam Lassek

Reputation: 35505

Each controller action is executed in a separate request, so you are losing the values in between.

You probably need to use session, or better yet flash to store the title across requests.

def edit
  flash[:title] = @title = "Edit account"
  ...
end

def update
  ...
  if (flash[:title] == "Location")
    redirect_to wsp_location_path
  else
    redirect_to edit_wsp_path
  end
end

Upvotes: 3

Related Questions