8

Rails Form Technique - Using collection_select with Open Structs

 3 years ago
source link: https://fuzzyblog.io/blog/rails/2020/03/01/rails-form-technique-using-collection-select-with-open-structs.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Rails Form Technique - Using collection_select with Open Structs

Mar 1, 2020

IMG_0741.jpeg

I've written about Open Structs before:

To review, an Open Struct is a hash like data structure that responds to dot methods (i.e. .id or .name). I use these in a lot of different places and I just finished using them for a form collection_select operation.

The Rails collection_select form helper is really designed to work with database objects that you need to make pick lists from. The canonical usage is like this:

<%= form.label :project_id %>
<%= form.collection_select :project_id, current_user.projects.all, :id, :name %>

The expression current_user.projects.all is a list of all projects as an iterable ActiveRecord collection and what collection_select does under the hood is loop over the collection and call the .id and .name methods (.id is the value in the collection and .name is what's displayed). And this works great – until what you have to select isn't a database collection. And that, dear reader, is where open structs come out to play!

Here's what I just did:

Controller Side

@contexts = []
@contexts << OpenStruct.new(id: "web_browser_on_computer", name: "Web Browser (Desktop Computer)")
@contexts << OpenStruct.new(id: "mobile_app", name: "Mobile App")

This defines an array of open struct objects. And an array is an iterable collection just like the database collection so this implementation, despite being an entirely different underlying data structure, works just like the ActiveRecord collection based version.

View Side

And here's the view side:

<%= form.label :context %>
<%= form.collection_select :context, @contexts, :id, :name %>

Appearance

Here's how this looks by default and then when dropped down:

collection_select_open_struct01.png
collection_select_open_struct02.png

Posted In: #rails #open_struct


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK