お世話になります。
現在Railsを勉強中のプログラミングの初心者です。
色々分からないことが多く、質問の内容も分かりづらい部分があるかもしれませんが
どうかお力添え戴ければ幸いです。
今、ユーザーごとに食材在庫を管理するアプリを作っており、
categoryごとに分けた食材をcatrgoryボタンをクリックしたら、ajaxを使って画面遷移せずにcategoryごとの食材一覧を表示させようとしているのですが、表示がでてきません。
まず、食材登録のテーブルは下記のようにカラムがあります。
class CreateStocks < ActiveRecord::Migration def change create_table :stocks do |t| t.references :user, index: true, foreign_key: true t.string :category t.string :foods_name t.integer :number t.datetime :limit t.timestamps null: false end end end
食材登録する際に【野菜】【お肉】【お魚】などをcategoryに登録します。
下記で、categoryボタンを作って、クリックしたらajaxでリクエストが飛ぶようにしてます。
<div class="btn-group-vertical"> <button class="btn"><%= link_to "野菜", get_category_user_path("野菜"), remote:true %></button> <button class="btn"><%= link_to "果物", get_category_user_path("果物"), remote:true %></button> <button class="btn"><%= link_to "お肉", get_category_user_path("お肉"), remote:true %></button> <button class="btn"><%= link_to "お魚", get_category_user_path("お魚"), remote:true %></button> <button class="btn"><%= link_to "乳製品", get_category_user_path("乳製品"), remote:true %></button> <button class="btn"><%= link_to "卵", get_category_user_path("卵"), remote:true %></button> <button class="btn"><%= link_to "その他", get_category_user_path("その他"), remote:true %></button> </div> <div class="col-xs-6"> <table border="1"> <tr> <th>食材名</th> <th>個数</th> <th>期限</th> </tr> <tr id="stock_food"></tr> </table> </div>
ajaxで飛んできたリクエストを受け取るget_categoryメソッドをコントローラーで作って、ボタンのcategoryと該当する食材を@foodsに入れてます。
def get_category @foods = current_user.stocks.where(category: params[:id]) end
@foods を get_category.js.erb で <tr id="stock_food"></tr> に展開して表示されるように記述してます。
$('#stock_food').append( <% @foods.each do |fd| %> <td><%= fd.foods_name %></td> <td><%= fd.number %></td> <% if fd.limit.present? %> <td><%= fd.limit.strftime('%Y年%m月%d日') %></td> <% end %> <% end %> );
ただ、実行してもviewにはなにも表示されません。
javascriptもあまり得意でなく、検索して見ながら記述したので間違いがあるのかもしれませんが、原因がわかりません。
ご指摘頂けると幸いです。
あなたの回答
tips
プレビュー