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'.
yes, multiple submit buttons can include in the html form.
Basically just add the buttons to the DOM inside my form and collect the values from the event that I have access to inside of the submit handler. Why not use onClick for each button? You can have a separate handler for each, or pass an argument to a shared handler.
This was covered in Railscast episode 38. Using the params
hash to detect which button was clicked is the correct approach:
View:
<%= submit_tag 'Create' %> <%= submit_tag 'Create and Add Another', name: 'create_and_add' %>
Controller:
if params[:create_and_add] # Redirect to new form, for example. else # Redirect to show the newly created record, for example. end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With