简体   繁体   中英

How to use collection_select in rails 4 from a model module?

I am trying to use collection_select tag for the default _form.html.erb using a concern/module, I need to set a hash including some department names.

Here is my app/models/concerns/SetDepartment.rb

    module Set_Department

     extend ActiveSupport :: Concern

     def department
       department {
         1=>"Amatitlán",
         2=>"Chinautla",
         3=>"Chuarrancho"
       }
     end
   end

Here is the model where I want to call the department method:

    class Aplicante < ActiveRecord::Base
      include SetDepartment
      validates :titulo_id, :primer_nombre, 
      :primer_apellido, :dpi, :direccion_linea_1,:zona, :department_id, :username, 
      presence: true
      validates :dpi,:username, uniqueness: true
      has_secure_password
    end

Now, I need to include this hash in a collection_select tag on my app/views/applicants/_form.html.erb

      #...

        <div class="field">
        <%= f.label :department_id %><br>
        <%= f.collection_select :department_id, Aplicante.department, Aplicante.department %>
        </div>
      #...

Obviously, this does not work but I can not think on anything else. I have searched through the internet but I just get tough explinations and none of them involves a module... is it even possible?

Solved!

I was using the wrong method..

We can not use a collection_select helper with a hash, instead, we need to use the regular select method.

Collection_select is used when you have two models and you want to combine their different values in a drop down menu.

Information about how to use the select tag with a hash here:

http://apidock.com/rails/ActionView/Helpers/FormTagHelper/select_tag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM