0

I would like to create a drop down list with Ruby on rails from the model "Company" which has a item call "name". I would like to length of the dropdown list to be as long as Company.count (dynamic)

For example for 3 element in "Company":

 <%= f.select :company_brand, [[Company.find(1).name, Company.find(1).id],[Company.find(2).name, Company.find(2).id],[Company.find(3).name, Company.find(3).id]]%>

4 Answers 4

1

collection_select (documentation) will provide what you need:

collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})

Returns and tags for the collection of existing return values of method for object's class. The value returned from calling method on the instance object will be selected. If calling method returns nil, no selection is made without including :prompt or :include_blank in the options hash.

The :value_method and :text_method parameters are methods to be called on each member of collection. The return values are used as the value attribute and contents of each tag, respectively. They can also be any object that responds to call, such as a proc, that will be called for each member of the collection to retrieve the value/text.

For your use case, this would mean changing the code to:

<%= f.collection_select(:company_brand, Company.all, :id, :name) %>
Sign up to request clarification or add additional context in comments.

Comments

1

You can do like this:

<%= select(:company_brand, Company.all.collect {|c| [ c.name, c.id ] }, { include_blank: true }) %>

Comments

1
#League - form.html.erb
<%= f.collection_select(:game_id, Game.order(:title), :id, :title, {prompt: true}, {class: 'form-control col-md-7 col-xs-12', required: "required"})%>

#.html_output
<select class="form-control col-md-7 col-xs-12" required="required" name="league[game_id]" id="league_game_id"><option value="">Please select</option>
    <option value="2">csgo</option>
    <option value="1">dota2</option>
</select>

Comments

0

You can try this i think this will help you.

<%= f.select :company_brand, options_from_collection_for_select(Company.all, "id", "name") %>

2 Comments

Can you explain your code a little? How is it different from OP's example?
@eventHandler please refer this link which gives more clear explanations about form helper in ruby on rails. guides.rubyonrails.org/v2.3.11/form_helpers.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.