1

I'm working on some app and I have 2 models. Categories in which I create category names and Question. Category has_many questions and Question belongs_to Category.
I've added category_id to Question model.

Now I need to take all Category_names and display them in form where I create Question so User can choose in which category_name will save question.

I've tried something like this in firs line of code but not working.

<%= f.input :category_id, Category.all.map(&:name) %>
<%= f.input :question_name, wrapper: :vertical_text_input, as: :text %>
<%= link_to "Markdown help", "http://assemble.io/docs/Cheatsheet-Markdown.html", target: "_blank", class: "right" %>
<%= f.input :answer %>
<%= f.input :image, as: :attachinary %>

QUESTION: How to display all Category names in form where I create new Questions?

RubyDigger19
  • 835
  • 13
  • 38

2 Answers2

2

you may wanna use a select box and use the collection select rails helper :

f.collection_select(:category_id, Category.all, :id, :name)
nicolas
  • 900
  • 6
  • 16
  • It works but when I open page where this form is, it's not showing me collection_select until I refresh page. Then loads select field. Don't know why is this happening.. – RubyDigger19 Apr 24 '16 at 10:31
1

Also you can use this way.

<%= f.select :category_id, Category.all.map(&:name), {prompt:"Choose Category"}%>

@Jhon suggestion.

<%= f.select :category_id, Category.pluck(:name), {prompt:"Choose Category"}%>
7urkm3n
  • 6,054
  • 4
  • 29
  • 46