Ruby rails edit attribute using button

Suppose I have an @transaction object that displays / transaction / id

def show @transaction = Transaction.find(params[:id]); end 

In show.html.erb, I want to have a button that, when clicked, changes one of the attributes of a transaction. How to do it?

In show.html.erb, I have

 <%= form_for @transaction do |t| %> <%= t.label :id %> : <%= @transaction.id %><br /> <%= t.submit "pay" %> <% end %> 

EDIT: I think I may have misled the question. The button code above generates this html:

 <input id="transaction_submit" name="commit" type="submit" value="pay" /> 

When I click the button, the update method in the controller is called. How to transfer a value from a button to a specific action in the update method? For example, suppose button1 changes the name of a transaction to "lalala". How to do it?

 def update // if button1 is pressed, change transaction.name to lalala // if button2 is pressed, change transaction.amount to bobobo end 
+4
source share
2 answers

Use different shapes for each button:

  <%= form_for @transaction do |t| %> <%= t.hidden_field :name, :value=>"mike" %> <%= t.submit "change_name_to_mike" %> <% end %> <%= form_for @transaction do |t| %> <%= t.hidden_field :name, :value=>"john" %> <%= t.submit "change_name_to_john'" %> <% end %> 
+4
source

Or do it through Ajax. For example, you might have link_to "Delete votes", delete_votes_path(user), :remote => true (or something else). Then the action can do whatever it needs, and possibly return JavaScript that updates div / span / what with the new value, and also displays a message, etc.

It's a little more elegant, and Rails makes it easy to create small pieces of Ajaxy functionality that extend UX but take a little effort. A trivial, naive example here .

+1
source

All Articles