Search code examples
ruby-on-railsransack

Trying to map id to a name using form in Rails


I'm using search gem Ransack for search ability in my app. In my form I seem to have it all working however I can only get the form to show either a) the id or b) the object itself. I cannot seem to map it correctly to the name of the data and not it's id.

Any thoughts?

Form code:

<!-- office type -->
<%= f.collection_select :office_type_id_gteq, Desk.all, :id, :office_type_id, include_blank: "Office type", class: "form-control" %>

Models & Schema:

class OfficeType < ActiveRecord::Base
    has_many :desks

end

class Desk < ActiveRecord::Base

    belongs_to :office_type

end

schema

  create_table "desks", force: :cascade do |t|
    t.string   "listing_name"
    t.integer  "min_days"
    t.integer  "max_days"
    t.text     "description"
    t.string   "location"
    t.integer  "accommodate"
    t.integer  "user_id"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.integer  "daily_rate"
    t.integer  "office_type_id"
    t.integer  "desk_type_id"
    t.string   "amenity_ids",    default: "--- []\n"
    t.float    "latitude"
    t.float    "longitude"
    t.boolean  "active"
  end


  create_table "office_types", force: :cascade do |t|
    t.string   "office_type"
    t.integer  "desk_id"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

So as it stands I can see the office_type_id show in my collection on the drop down in the form. I can change this to office_type but this brings in the object itself and not the string value called office_type.

Was trying to map the office_type_id to the office_type string but can't seem to get that working. I know the Desk.all could be added to a variable in controller it's juts for ease i've it directly in form to see if can get to work.

Thanks again.


Solution

  • https://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select

    This tells you how to use collection_select. But first of all I think you're structuring your models wrong. If an office type has many desks, then it cannot have a desk ID, as this will link it to just one desk. You'll need to remove this column, as the relationship comes through the desk's office type ID

    If I"m understanding correctly then what you want is:

    <%= f.collection_select :office_type_id, OfficeType.all, :id, :office_type, include_blank: false, class: "form-control" %>
    

    This will create a dropdown menu for the attribute 'office_type_id', taking all of the Office Types as options, sending their ID through when selected, and using their Office Type attribute to decide what to display on the dropdown.