Orsay Orsay - 1 month ago 6
Ruby Question

Undefined method when I loop to display a f.select in form

I would like to have a list in my form with all my project statuses.

The field status exist in the database. When I run something like

Project.first.status
it works fine but it doesn't when I loop into it.

When I run the following code I get :


undefined method `statuses' for Class...


new_form

<%= form_for [@context, @project], validate: true do |f| %>
<%= f.label "status" %>
<%= f.select(:status, Project.statuses.keys.map{ |status| [I18n.t("#{status}"), status] %>


SCHEMA

create_table "projects", force: :cascade do |t|
t.string "title"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "status"
end

Answer

You cannot use an assosciation directly on a Class so Project.statuses is wrong.

use select on Class and then map them

Project.select(:status).map(&:status).uniq

<%= form_for [@context, @project], validate: true do |f| %>
       <%= f.label "status" %>
       <%= f.select(:status, Project.select(:status).map{ |status| [I18n.t("#{status}"), status]}.uniq %>