views:

36

answers:

2

Say I have an Article model, and in the article 'new' view I have two buttons, "Publish" and "Save Draft".

My question is how can I know which button is clicked in the controller.

I already have a solution but I think there must be a better way. What I currently used in the view is:

<div class="actions">
  <%= f.submit "Publish" %>
  <%= f.submit "Save Draft", :name => "commit" %>
</div>

So in the controller, I can use the params[:commit] string to handle that action.

def create
  @article = Article.new(params[:article])
  if params[:commit] == "Publish"
    @article.status = 'publish'
    // detail omitted
  end

  @article.save
end

But I think using the view related string is not good. Could you tell me another way to accomplish this?

UPDATE: Since these buttons are in the same form, they're all going to the 'create' action, and that's OK for me. What I want is to handle that within the create action, such as give the Article model a 'status' column and holds 'public' or 'draft'.

A: 

I remember coming across this problem once. You cannot keep two buttons and then call some action based on the params[:commit]. the submit button onclick is going to call the url the form refers to. There are certain bad ways to get the desired behavior. Keep a button to call the action the form refers to and to get another button to call a action, I used a link_to and then changed the styles to match a button. Also, alternatively you can use jQuery to change the url the form would call, hence deciding what action is invoked at run-time. Hope this helps.

alokswain
Sorry I forgot to mention that I was trying to handle that in the same create action, I've updated the question. But I also learned your tips on how to use jQuery to change the url of the form, it's helpful. Thanks.
kinopyo
+1  A: 

This was covered in Railscast episode 38. Using the params hash to detect which button was clicked is the correct approach.

John Topley
I've been watching Railscasts episode for a week but I definitely missed this one. It seems to be the same as my code, both use params hash, but it did a better work and I also improved my code. Thanks a lot!
kinopyo