LoginSignup
12
13

Rails - コントローラで生成したデータをJSで利用したい。

Last updated at Posted at 2015-08-17

いろいろ方法があるうちの一つ。
今後も便利に使えそうなのでメモ。

Controller

コントローラでデータを準備し、テンプレートに渡す目的でインスタンス変数に格納する。

movings_controller.rb
  #...
  def show
    #...
    @itemNameSuggestions = Ingredient.select(:category).pluck(:name),
    @roomSuggestions     = Room.select(:name).pluck(:name),
    @categorySuggestions = @moving.moving_items.select(:category).distinct.pluck(:category)
  end
  #...

Template

ID付きの空タグを作り、data属性にコントローラから受け取ったデータを書き込む。

show.html.haml
= content_tag :div, "", id: "suggestions", data: { items: @itemNameSuggestions,
  rooms: @roomSuggestions, categories: @categorySuggestions }

JS

IDでタグを探し、dataメソッドでデータを取り出す。

moving_items.coffee
jQuery ->

  $('#moving_item_name').autocomplete
    source: $('#suggestions').data('items')

  $('#moving_item_room').autocomplete
    source: $('#suggestions').data('rooms')

  $('#moving_item_category').autocomplete
    source: $('#suggestions').data('categories')

参考資料

12
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
13