Reputation: 3940
Ruby on Rails 4
In my model I have:
@category_check = ['cables', 'printers', 'monitors', 'accessories', 'towers', 'interaction']
It is used for a validates, now I want to display the array as options in my form. This does not work:
<%= f.label :category %><br>
<%= f.collection_select :category, @category_check, {prompt: "Select Category"}, class: "input-lg" %>
Do I have to make another instance variable in my controller or is there a way to display each in a drop down from the model variable? Thank you
Upvotes: 0
Views: 407
Reputation: 164
You are probably missing one parameter on the method call:
<%= f.collection_select :category, @category_check, {prompt: "Select Category"}, class: "input-lg" %>
should be:
<%= f.collection_select :category, :category_id, @category_check, {prompt: "Select Category"}, class: "input-lg" %>
Upvotes: 0
Reputation: 4966
You should be able to access that array through the model, assuming you have one instantiated:
@my_model.category_check
However it looks like those categories are static, so ideally they'd be a class-level constant:
class MyModel
CATEGORY_CHECK = ['cables', 'printers', 'monitors', 'accessories', 'towers', 'interaction']
end
Then you could access it anywhere, without an instance of the class around:
MyModel::CATEGORY_CHECK
As Lalitharyani mentions in his answer, you'll also need to provide name and value methods to call on each item of the array so that the form helper knows what to display.
Upvotes: 1
Reputation: 3323
You need to call something like this
<%= f.collection_select :category, @category_check, :to_s, :to_s, {prompt: "Select Category"}, class: "input-lg" %>
This will pass :to_s to each element of the the @category_check collection.
Upvotes: 1