Reputation: 701
I have in my students table :
id | fname | gname | course | year |
----------------------------------------
1| user 1| user 1| IT | 5 |
----------------------------------------
2| user 2| user 2| CompE | 3 |
----------------------------------------
3| user 3| user 3| Nursing| 2 |
In my controller I am using *HASH to display the Student info*
def index
@students = Student.all
@studentlist = HASH.new
@students.each do |s|
@studentlist[s.id] = s
end
end
In my Index View I have this
<%=form_tag "/students/update_year" do%>
<table>
<tr>
<th>id</th>
<TH>Family Name</TH>
<TH>Year</TH>
</tr>
<%@studentlist.each_key do |key|%>
<tr>
<td><%=@studentlist[key].id%></td>
<td><%=@studentlist[key].fname%></td>
<td><%=collection_select(:student,:year,Student.select('distinct year') , :year , :year ,:selected=>@studentlist[key].year %></td>
</tr>
<%end%>
</table>
<%=submit_tag("Update")%>
This my controller update_year action :
def update_year
@students = Student.all
@studentlist = HASH.new
@students.each do |s|
@studentlist[s.id] = s
@studentlist.each_key do |key|
@student = Student.find(@studentlist[key].id)
@student.update_attributes(params[:student])
end
end
end
It will not update or the value will not be updated to I have set on my collection_select
Please help me ! Thank You.
Upvotes: 0
Views: 124
Reputation: 29599
I hope you learn something from this answer.
def index
@students = Student.all
@years = Student.uniq.pluck(:year)
end
index.html.erb
<% @students.each do |student| %>
<tr>
<td><%= student.id %></td>
<td><%= student.fname %></td>
<td>
<%= hidden_field_tag 'student[][id]', student.id %>
<%= select :student, :year, @years, { selected: student.year }, { name: 'student[][year]' } %>
</td>
</tr>
<% end %>
The code above creates your table without using a hash. It also creates fields that will generate a hash when you submit the form. The hash will look like
params[:student] = [{ id: 1, year: 1 }, { id: 2, year: 2}]
id
is the student_id
, year
is the selected year in the dropdown. Given this, you can use the following code for update_year
def update_year
params[:students].each do |student|
student = Student.find(student[:id])
student.update_attributes(year: student[:year])
end
end
DISCLAIMER: The code above isn't tested and was written trying to help you understand how you can solve your issue.
Upvotes: 1
Reputation: 373
Upvotes: 0