0

I'm trying to figure out how to scope the options of one select field after an option of another select field is selected.

Once a board is selected in the 'boards' select field, only the lists that belong to that board should appear in the 'lists' select field.

A common example of this is seen on signup forms, where when a country is selected in the 'Country' select field, the 'State/Province' select field only shows the States/Provinces of that country.

Associations

class User < ActiveRecord::Base
  has_many :boards
  has_many :cards, through: :boards
end

class Board < ActiveRecord::Base
  belongs_to :user
  has_many :cards
end

class List < ActiveRecord::Base
  belongs_to :board
  has_many :cards
end

class Card < ActiveRecord::Base
  belongs_to :board
end

Instance Variables used in the form

class CardsController < ApplicationController
def edit
  @card = current_user.cards.find(params[:id])
  @board = @card.board
  @lists = @board.lists
end
end

Form

<%= form_for @card do |f| %>
  ...
  #show the user's boards
  <%= f.collection_select(:board_id, @boards, :id, :name) %>

  #show the lists of a board
  <%= f.collection_select(:list_id, @lists, :id, :name) %>
  ...
<% end %>
John.Mazzucco
  • 269
  • 1
  • 3
  • 5
  • You need to use ajax (or have a dictionary in the client side) to fetch updated options for the second select when the user selects a value. There are quite a few gems and jquery plugins that accomplish this. How to create one from scratch is way too lengthly for a stackoverflow answer. – max Sep 30 '16 at 15:15
  • 1
    a bunch of javascript... ive done this with a combination of backbone, handlebars templates, and gone... but i believe you can do this more simply with ajax. here is a tutorial i found with a searach for ruby on rails dynamic drop down boxes https://kernelgarden.wordpress.com/2014/02/26/dynamic-select-boxes-in-rails-4/ – Eric Sep 30 '16 at 15:19

0 Answers0