Skip to content

Instantly share code, notes, and snippets.

@maecha

maecha/CLI

Last active Apr 6, 2018
Embed
What would you like to do?
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