いろいろ方法があるうちの一つ。
今後も便利に使えそうなのでメモ。
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')