現状
railsチュートリアルに沿って、アプリケーション開発をしています。いいね機能を搭載し、ajaxをつけてようとしているのですが、リロードしないと表示が変わりません。submitのボタンを押すと、その場では何も変化がないような挙動をし、リロードすると、いいね機能が実行され、画面にも変化が現れる状態です。以下に、関連していると思われるコードを載せておきます。ネット上にあるサイトを参考にして、turbolinksのgem,jsでの読み込みをコメントアウトしてあります。ほかに必要な情報があれば、手間をおかけしますがよろしくお願いします。読みづらいコードかもしれませんが、どうかよろしくお願いいたします。
エラーコード
ruby
1ActionView::Template::Error (undefined local variable or method `micropost' for #<#<Class:0x00000000051a4bb8>:0x00000000051d2888> 2Did you mean? micropost_url)
上記のエラーは、create.js.erb,destroy.js.erbの両方に見られます。
_micropost.html.erb内でeach文を使用して、@microposts.each do |micropost|としているのですが、jsファイルにはこのmicropostが検知されず、このエラーが出てしまっているのでしょうか?
コード
ruby
1(favorites_controller.rb) 2 3def create 4 @micropost = Micropost.find_by(id: params[:micropost_id]) 5 current_user.like(@micropost) 6 respond_to do |format| 7 format.html { redirect_back(fallback_location: root_path) } 8 format.js 9 end 10 end 11 12 def destroy 13 @micropost = Micropost.find(params[:micropost_id]) 14 current_user.unlike(@micropost) 15 respond_to do |format| 16 format.html { redirect_back(fallback_location: root_path) } 17 format.js 18 end 19 end
ruby
1(favorites/_like_button.html.erb) 2 3<%= form_for(current_user.favorites.build, remote: true) do |f| %> 4 <%= hidden_field_tag :micropost_id, micropost.id %> 5 <%= button_tag :type => "submit", :class => "star icon" do %> 6 <i class="fa fa-star-o" id="likes"><%= micropost.like_users.count %></i> 7 <% end %> 8<% end %>
ruby
1(favorites/_unlike_button.html.erb) 2 3<%= form_for(current_user.favorites.find_by(micropost_id: micropost.id), 4 html: { method: :delete }, 5 remote: true) do |f| %> 6 <%= hidden_field_tag :micropost_id, micropost.id %> 7 <%= button_tag :type => "submit", :class => "star icon" do %> 8 <i class="fa fa-star" id="likes"><%= micropost.like_users.count %></i> 9 <% end %> 10<% end %>
ruby
1(favorites/_like_form.html.erb) 2 3<% unless current_user?(micropost.user) %> 4 <div id="like_form"> 5 <% if current_user.like?(micropost) %> 6 <%= render 'favorites/unlike_button', micropost: micropost %> 7 <% else %> 8 <%= render 'favorites/like_button', micropost: micropost %> 9 <% end %> 10 </div> 11<% end %>
ruby
1(microposts/_microposts.html.erb) 2 略 3 <div id="like_btn"> 4 <% if logged_in? %> 5 <%= render 'favorites/like_form', micropost: micropost %> 6 <% end %> 7 </div> 8 略 9
ruby
1(favorites/create.js.erb) 2 3$("#like_form").html("<%= escape_javascript(render('favorites/unlike_button')) %>");
ruby
1(favorites/destroy.js.erb) 2 3$("#like_form").html("<%= escape_javascript(render('favorites/like_button')) %>");
ruby
1(config/application.rb) 2 3config.action_view.embed_authenticity_token_in_remote_forms = true
html
1<%= csrf_meta_tags %> 2<%= stylesheet_link_tag 'application', media: 'all','data-turbolinks-track': 'reload' %> 3<%= javascript_include_tag 'application','data-turbolinks-track': 'reload' %>
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/05/30 03:47