Ruby on Rails: re-order checkbox tag

回眸只為那壹抹淺笑 提交于 2019-12-24 17:27:39

问题


I have an app where a user can enter projects into a database. One of the fields allows the user to pick multiple technologies. I want the list of technologies to appear in alphabetical order, because at the moment, they appear in the order they were entered into the database.

Here is my new action in my project controller:

def new
    @project = Project.new
        @technol = Technol.new(params[:tech])

        @all_technols = Technol.all
        tech_ids = params[:technols][:id].reject(&:blank?) unless params[:technols].nil?


        @project_technol = @project.projecttechnols.build

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @project }
    end
  end

Here is part of my new view:

<div class="tech" STYLE="text-align: left;">
  <b>Technologies:</b>
  <style>
    .split { text-align:left; }
  </style>


  <p><ul> 

  <% for technol in Technol.all %> 
   <li class="split"> 
    <%= check_box_tag "project[technol_ids][]", technol.id,  @project.technols.include?(technol) %> 
    <%= technol.tech %> 
   </li> 

  <% end %> 
 </ul> 
 </p> 

Does anyone have any ideas? I am new to rails so please remember this when trying to answer. Thanks in advance.


回答1:


You should order the list of your thechnologies:

@all_technols = Technol.order('tech ASC') # in the controller's action

And then use this variable in the view instead of calling Technol.all second time:

<% @all_technols.each do |technol| %> 
  your code without changes here
<% end %>


来源:https://stackoverflow.com/questions/13269961/ruby-on-rails-re-order-checkbox-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!