Ruby on Rails: re-order checkbox tag

2019-08-12 01:52发布

问题:

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