views:

30

answers:

1

Hi,

I am trying to set up a preview button in an edit form based on the railscast by Ryan Bates. There are two buttons [edit] and [update].

When the user clicks the preview button, the "update" function in the controller is called. If I simply set the @article variable based on a find of the article table (as per below controller) the preview button resets the values in the form to the saved data and I lose my edits.

Is there a way I can have a preview mode for updates? New works fine, only edit has this issue.

  def update
    @article = Article.find(params[:id])

    if params[:preview_button] || [email protected]_attributes(params[:article])
      render :action => 'edit'
    else
      respond_to do |format|
        format.html { redirect_to(@article, :notice => 'Article was successfully updated.') }
      end
    end
  end

Edit: I tried using the below code instead

if params[:preview_button] || [email protected]_attributes(params[:article])
  @article = Article.new(params[:article])
  render :action => 'edit'
else

Which preserves the data, however there's a side-effect. Clicking the preview button from [http://localhost:3000/articles/4/edit] redirects to [http://localhost:3000/articles/4] clicking again here goes to the new view [http://localhost:3000/articles].

+1  A: 
if params[:preview_button] || [email protected]_attributes(params[:article])

Only in the case of the preview_button param not existing is the article being updated.

You want something like:

@article.attributes = params[:article]
if params[:preview_button] or [email protected]
  render :action => 'edit
mark
Be very, very careful with mixing `||` and `or`. In Ruby, they are not the same thing.
vonconrad