0

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")%>
  • I want to change the year of the students and click the Update but my Problem is when I Update it all of the value in year column will be change and will have the same value.

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.

4

2 回答 2

1

我希望你能从这个答案中学到一些东西。

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 %>

上面的代码在不使用哈希的情况下创建您的表。它还创建在您提交表单时将生成哈希的字段。哈希看起来像

params[:student] = [{ id: 1, year: 1 }, { id: 2, year: 2}]

idstudent_id,year是下拉列表中选定的年份。鉴于此,您可以使用以下代码update_year

def update_year
  params[:students].each do |student|
    student = Student.find(student[:id])
    student.update_attributes(year: student[:year])
  end
end

免责声明:上面的代码未经测试,旨在帮助您了解如何解决问题。

于 2013-07-18T09:35:02.363 回答
0
  1. 为什么要使用哈希来显示表格?
  2. 在您的 update_year 操作中,让所有学生都从 db 中获取是不明智的,因为这很耗时,而且您不需要它。
于 2013-07-18T09:20:12.090 回答