Nick
Nick

Reputation: 597

Button event trigger

I am having trouble understanding as how do you trigger specific button event when using Ruby on Rails. For example I have a mini form inside a table as so (View side of MVC):

<%= form_tag do %>
<% if student.floor_pref == '1st' %>
    <td><%= select_tag 'room', options_for_select(@first_floor.map { |value| [value,value]}, @selected_room) %></td>
<% end %>
<% if student.floor_pref == '2nd' %>
    <td><%= select_tag 'room', options_for_select(@second_floor.map { |value| [value,value]}, @selected_room) %></td>
<% end %>
<% if student.floor_pref == '3rd' %>
    <td><%= select_tag 'room', options_for_select(@third_floor.map { |value| [value,value]}, @selected_room) %></td>
<% end %>

<td><%= submit_tag 'Update' %></td>
<% end %>

How do I tell the controller that when the Update button is clicked inside the view to for example execute this code:

a = Student.find(3)

a.room_number = '2105'
a.save

Upvotes: 1

Views: 1146

Answers (2)

Prasad Surase
Prasad Surase

Reputation: 6574

u should specify a route(a controller action to which the data is to be submitted) in the form tag. refer http://apidock.com/rails/ActionView/Helpers/FormTagHelper/form_tag for more details. considering that ur action is for 'edit' action from students controller and that data is to be posted to 'update', the view can be defined as

<%= form_tag student_path(@student), :method => :put do %>
  ...
  <$= submit_tag 'Update' %>

and in the 'update' method, u can write the code to update student with the received params. I think u need to study basic rails functioning since it will save u time in future. u can refer http://guides.rubyonrails.org/getting_started.html Also, prefer using form_for rather than form_tag.

Upvotes: 2

user229044
user229044

Reputation: 239311

Your button should be triggering a post-back to the server. You need to define an action in your controller, a route to reach that action, and set your forms action attribute to that route. Your action can then update the models and respond with a success or error message.

Upvotes: 2

Related Questions