Rails 3 - forms custom action-based submit button?

Currently, I have several forms that I am trying to change a button that sends it if I am in an edit action or a new action. I had two forms, but it smelled bad, and now I just use only one form.

At the end of my partial, I have something like this at the end of my forms:

<p> <% if controller.action_name == 'new' %> <%= f.submit "Create", :class => "pink_button"%> or <% elsif controller.action_name == 'edit' %> <%= f.submit "Update", :class => "pink_button"%> or <% end %> <%= link_to "cancel", :back %> </p> 

Thus, if I create a new one, the button reads “Create,” and if it is an update that the user is trying to complete, the button reads “Update.” This works fine until the form is submitted and validation fails.

In my controller, I break things that don't work like this:

 def update @list = current_user.lists.find(params[:id]) if @list.update_attributes(params[:list]) redirect_to list_path(@list), :notice => "List '#{@list.name}' updated." else render :action => 'edit' end end 

Thus, the form is simply redrawn. The problem is that I'm no longer on the path of editing. This means that my form button is no longer displayed.

Is there an agreement on what I'm trying to do?

thanks

+6
source share
3 answers

Yes, this is handled in Rails with i18n by default. Translations are in the ActionView and look like this:

 en: helpers: select: # Default value for :prompt => true in FormOptionsHelper prompt: "Please select" # Default translation keys for submit FormHelper submit: create: 'Create %{model}' update: 'Update %{model}' submit: 'Save %{model}' 

All you have to do is f.submit (without transmitting “Create” or “Change”, etc.), and translations will do the rest. You can overwrite them by dropping the above yaml into local locales.

If you need to set the class, you can pass nil, for example. f.submit nil, :class => 'whatev'

+14
source

Rails way is to check if a record is new or not:

 @list.new_record? ? "Create" : "Update" 
+13
source

Does Rails have a persisted? method persisted? to determine if the object has been preserved.

If you use erb do

 <%= f.submit (@list.persisted? ? 'Create' : 'Update) %> 

If you use haml, use

 = f.submit (@list.persisted? ? 'Create' : 'Update') 

See http://apidock.com/rails/ActiveRecord/Persistence/persisted%3F for details

0
source

Source: https://habr.com/ru/post/894872/


All Articles