开发者

ruby rails edit attribute using a button

Suppose I have an object @transaction that gets shown /transactions/id

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

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

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 with the question. The button code above generates this html:

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

When I click on the button, the "update" method in the controller is called. How do I pass the value from a button to a specific action in the u开发者_StackOverflowpdate method? For example, suppose button1changes the transaction.name to "lalala". How do I do this?

def update
  // if button1 is pressed, change transaction.name to lalala
  // if button2 is pressed, change transaction.amount to bobobo
end


Use a different form 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 %>


Or do it via Ajax. For example, you could have a link_to "Delete votes", delete_votes_path(user), :remote => true (or whatever). The action can then do whatever it needs to, and possibly return JavaScript that will update a div/span/whatever with the new value, as well as display a message, and so on.

This is a bit more elegant, and Rails makes it pretty easy to create little bits of Ajaxy functionality that ramp up the UX, but take little effort. Trivial, naive example here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜