Skip to content

Instantly share code, notes, and snippets.

@maecha
Last active April 6, 2018 06:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maecha/c204f0a0807680fc5e1d654a83a8b635 to your computer and use it in GitHub Desktop.
Save maecha/c204f0a0807680fc5e1d654a83a8b635 to your computer and use it in GitHub Desktop.
Update select box when another one is updated. / E.g. Hoge and Fuga are 'one-to-many relationship', and use a controller 'Piyo' without this association .
$(document).on 'turbolinks:load', ->
do ->
replaceSelectOptions = ($select, results) ->
$select.html $('<option value="">Please select</option>')
$.each results, ->
option = $('<option>').val(this.id).text(this.name)
$select.append(option)
replaceChildrenOptions = ->
getFugasPiyoPath = $(@).find('option:selected').data().getFugasPiyoPath
$selectFugas = $(@).closest('form').find('.js_piyos-new-select-fuga')
if getFugasPiyoPath?
$.ajax
url: getFugasPiyoPath
dataType: 'json'
success: (results) ->
replaceSelectOptions($selectFugas, results)
error: (XMLHttpRequest, textStatus, errorThrown) ->
replaceSelectOptions($selectFugas, [])
else
replaceSelectOptions($selectFugas, [])
$('.piyos-new-select-hoge').on
'change': replaceChildrenOptions
class PiyosController < ApplicationController
def new
@piyo = Piyo.new
@hoges = Hoge.all
.map{|h| h.name, h.id, data: { get_fugas_piyo_path: get_fugas_piyo_path(h) }]}
end
def get_fugas
if request.xhr?
hoge = Hoge.find(params[:hoge_id])
render json: hoge.fugas.select(:id, :name)
end
end
end
class Fuga < ApplicationRecord
validates :hoge_id
validates :name
belongs_to :hoge
end
class Hoge < ApplicationRecord
validates :name
has_many :fugas
end
class Piyo < ApplicationRecord
end
= form_for @piyo, url: piyos_path do |f|
label
'Hoge
= select_tag :hoge_id,
options_for_select(@hoges),
{ class: 'piyos-new-select-hoge', prompt: t('helpers.select.prompt') }
label
'Fuga
= select_tag :fuga_id,
[],
{ prompt: true },
{ class: 'js_piyos-new-select-fuga', required: true }
$ ruby -v
ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux]
$ bundle exec rails -v
Rails 5.1.4
Rails.application.routes.draw do
resources :piyos, only: [:new, :create] do
get :get_fugas
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment