Sunset road

Custom Attributes for Rails Select Helper

Thursday January 19, 2017

For context, I was building a feature for this blog which would include an attribution card for the writer of a post (which you can see at the bottom of the article). Because the person publishing the post would not necessarily be the person who wrote it, I wanted to be able to attach the contributor_id to the post in order to include the correct attribution when published.

There is a set of routes available to the admin, which creates and updates the contributors, and each contributor has an associated id. The goal here is to show a selectdropdown in the posts#new page, which shows the contributors' names, but saves the id upon save.

Because we want to be able to make the contributor selection from the new and edit post views, we need to first create an instance variable in the posts_controller to give access to the contributor information.

# posts_controller.rb

# GET /posts/new
def new
  @post =
  @contributors = Contributor.all

# GET /posts/:id/edit
def edit
  @contributors = Contributor.all

We can use the select helper on a form builder to easily set up the select options as needed.

# posts/_form.html.erb
<%= form_for(@post) do |f| %>
  // other form fields omitted for brevity
  <%= :contributor_id,{ |c| [,]}, :include_blank => "-- No contributor --" %>
<% end %>

Here we define what column this will be submitting to as :contributor_id, and map over all existing contributors to identify the name and id. These will be assigned as the element text and value attribute, respectively. :include_blank also offers a way of including a blank option, with no value.

Below is an example of what will be rendered.

# rendered HTML
<select name="post[contributor_id]" id="post_contributor_id">
  <option value="">-- No contributor --</option>
  <option value="1">Robin Hamill</option>
  <option value="2">Jess Jones</option>

Written by Robin Hamill

Robin is an independent web application and ecommerce developer living in Toronto. He builds intuitive and functional web apps that engage users and solve problems. He's also excited about climbing rocks, travelling and learning all the things. 💎⛪️