问题
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.
回答1:
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'))
回答2:
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.
来源:https://stackoverflow.com/questions/9169011/getting-submit-button-label-to-be-create-model-instead-of-update-model-insid