开发者

rails, preview button in form question

开发者 https://www.devze.com 2023-01-20 09:27 出处:网络
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].

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] || !@article.update_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] || !@article.update_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/开发者_如何学Python4] clicking again here goes to the new view [http://localhost:3000/articles].


if params[:preview_button] || !@article.update_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 !@article.save
  render :action => 'edit
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号