2
votes

I am rendering a form using form_for with an existing model. I would like to submit that model and get the next action to be performed to be the 'create' action. The docs have this example:

<%= form_for @post do |f| %>
  <%= f.submit %>
<% end %>

And say "In the example above, if @post is a new record, it will use “Create Post” as submit button label, otherwise, it uses “Update Post”."

I am relatively new to rails and am not sure what to make of the following stuff in the docs about customizing using I18n. How can I get the submit button to use "Create" when there's an existing record?

Clarification. . .

I the form_for is being rendered out of the new action, but I am passing it an existing object, so that fields can be prepolulated. I want it to then go to the create action, but it is going to the update instead.

Update. . .

I realize now that the issue is with the form_for and not the submit, but haven't yet figured out how to modify the form_for so that it sends to the create action.

2
Wait, why aren't you just sending then to the new action instead of the edit action then? If you edit a post it's kind of odd to not want to update - Azolo
@Azolo I am in the new action, trying to get it go to the edit action. Adding an update for clarification. . - John

2 Answers

3
votes

http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-submit

There are three options, you can either override it in the translations file (config/locales/en.yml).

en:
  helpers:
    submit:
      create: "Create %{model}"
      update: "Create %{model}"

Or you can specify a value on the submit method.

f.submit("Create Post")

Or, you can keep the translations file as it is by default and do:

f.submit(t('helpers.submit.create'))
0
votes

form_for will update a existing record instead of create, so basically you have to feed it a new record. The best way to do this is in the controller with record.dup. Something like

@post = @existing_post.dup

dup will create a shallow copy, allowing you to save it as a new record.