Search code examples
ruby-on-railsformsselect

Rails form select to return all params in an object


I have an list in my controller that looks like:

@relatives = [
    {
        id: '1',
        firstName: 'John',
        lastName: 'Smith',
        related: 'Father'
    },
    {
        id: '2',
        firstName: 'Sarah',
        lastName: 'Smith',
        related: 'Mother'
    }
]

I would like to put this list in a form select in my view. So it would be a drop-down of relatives, but it would only display the firstName field in the select. When the user selects an object and submits the form, the entire relative object would get passed to the controller in the params.

I was looking at the rails collection_select API, but couldn't figure out how to select an entire object in the form.


Solution

  • Alright, so I decided the best way to accomplish this is to just create a hash in my controller with the key being the display text and the value being a JSON representation of my object.

    Controller:

    @relatives = {
        "John" => "{id: 1, firstName: 'John', lastName: 'Smith', related: 'Father'}",
        "Sarah" => "{id: 2, firstName: 'Sarah', lastName: 'Smith', related: 'Mother'}"
    }
    

    Then in my view, I'll use options_for_select:

    f.select :relative, options_for_select(@relatives)
    

    When the user select a value and submits the form, the JSON string will be returned in the parameters as the value. From the controller, I'll just convert the JSON back to a model. Thanks for the help everyone.