user1234
user1234

Reputation: 43

Passing value of selected radio button in Rails

I'm working on an app in Rails that has teacher and student users. I want to list all the users that belong to a teacher and then let the teacher select a student to send a message to. I have a message model that has :content and :user_id for params. I want to set the :user_id based on the student selected. Here is my code:

<% @students = Student.all %>
    <% @students.each do |student| %>
          <% if student[:teacher_id] == @current_user.id %>
            <%= radio_button 'student', 'id', student.id %>
            <%= student.name %>
            <% @current_student = Student.find(student.id) %>
          <% end %>
    <% end %>

<%= form_for Message.new do |f| %>
   <%= f.text_area :content, class: 'messageTextarea' %> <br>
   <%= f.hidden_field :user_id, :value => @current_student.id %>
   <%= f.submit %>
<% end %>

So, I am looping through all students and printing those that have the same ID as the current user (the teacher) with a radio button. The radio button's value is the student's id. Then I want to pass that value to the :user_id of the message so it will then be retrievable for the student's view.

Currently, this code always passes in the value of the last student listed rather than the student selected. How can I change

<% @current_student = Student.find(student.id) %>

to find the student selected rather than the last one?

I did test this code using

 <%= f.hidden_field :user_id, :value => @current_user.id %>

and that did work, but I don't want the current_user's id, of course. Thanks for any help!

Upvotes: 0

Views: 2040

Answers (1)

Amro Abdalla
Amro Abdalla

Reputation: 584

If you want one form with radio buttons for the students, You gonna need a little bit JavaScript(Or Jquery), All you have to do is to put a listener on these radio button and when user click on one of them you change the hidden input of user_id name.

User example in this link will help you to put listener on a bunch of radio buttons and change another field value, it will be something like this:

$('input[type=radio][name=student[id]]').change(function() {
    $('#user_id').val($(this).val());
});

all you have to do is to make sure of name=student[id] and #user_id, if you used this approach you won't need this line anymore:

<% @current_student = Student.find(student.id) %>

Hope it works.

Upvotes: 1

Related Questions