Search code examples
ruby-on-railsform-helpers

How to have a select_tag drop down to associate items with lists


I have Item and List models and they are both associated. List has_many items and an item belongs_to a list

Schema:

  create_table "items", force: :cascade do |t|
    t.string   "name"
    t.integer  "list_id"
    t.datetime "created_at",                 null: false
    t.datetime "updated_at",                 null: false
    t.boolean  "completed",  default: false
  end

  create_table "lists", force: :cascade do |t|
    t.string   "name"
    t.integer  "user_id"
    t.datetime "created_at",                     null: false
    t.datetime "updated_at",                     null: false
    t.string   "permission", default: "private"
  end

I want to create a view (most likely items/new.html.erb) so when a user creates a new item, there will be a drop-down option for the user to select which list it belongs to. There will be a pre-defined list in the beginning (i.e.: List name: "Home", "Work", "Personal"). Any item that user makes will be associated to either one of those three.

Right now I have an Item new.html.erb view that takes in simple item name and list_id.

  <%= form_for @item do |f| %>

    <%= f.label :name %><br>
    <%= f.text_area :name, size: "24x12" %><br>
    <%= f.label :list_id %><br>
    <%= f.text_field :list_id %><br>
    <%= f.submit %>

<% end %>

Entering list_id manually is very inconvenient; after researching, it seems like select_tag is the best form helper to do the job.

enter image description here

enter image description here

How can I build a select_tag that displays 3 drop-down List that a user can choose from to associate an Item to List?


Solution

  • you can also use select since you use form to achieve this. since you mentioned List name are pre-defined you can do it like this:

     <%= f.select :list_id,  options_for_select([['Home', 1], ['Work', 2], ['Personal', 3]]), {:include_blank => true} %>
    

    Note: ['Home', 1] home has an id of 1 here {:include_blank => true} to include blank.