今、Ruby_on_railsでアプリを作っていて、良いね機能のajaxを実装しようとしています。
良いね機能は実装できたのですが、ajaxがうまくいかずにページを手動で処理しなければうまくいかない状態です。
ログでエラーが確認できたのですが、原因がわからない状態です。
ActionView::Template::Error (undefined method `id' for nil:NilClass):
1: ('#like-icon-post-<%= @product.id.to_s %>').
2: html('<%= link_to "いいね", like_path(@product, @like), method: :DELETE, remote: true, class: "loved hide-text" %>');
3:
というエラーなのですが、idにクラスが入っていないと思うのですが、何回やってもうまくいかず原因も特定できていないです。
ただ、処理自体はできているので、おそらくajaxで問題が起きていると思うのですが、どこで問題が起きているのでしょうか?
### <!---/likes/create.js.erb ---> ('#like-icon-post-<%= @product.id.to_s %>'). html('<%= link_to "いいね", like_path(@product, @like), method: :DELETE, remote: true, class: "loved hide-text" %>');
<!---likes/destroy.js.erb ---> $('#like-icon-post<%=@product.id.to_s %>').html('<%= link_to 'いいねを取り消す', product_likes_path(@product),method: :POST,remote: true,class: "love hide-text"%>');
#/likes_controller.rb class LikesController < ApplicationController def create @like=current_company.likes.build(like_params) @product = Product.find_by(id: params[:id]) if @like.save respond_to :js end end def destroy @like = Like.find_by(id: params[:id]) @product = Product.find_by(id: params[:id]) if @like.destroy respond_to :js end end private def like_params params.permit(:product_id) end end
<!--- /products/show.html.erb---> <div class="container"> <div class="row"> <div class="offset-md-2 col-md-8"> <br><br> <%= link_to @product.college.name, college_path(@product.college.id)%> <h2><%= @product.title %></h2> <p class="text-danger">¥<%= @product.price %></p> <div id="like-icon-post-<%= @product.id.to_s %>"> <% if @product.liked_by(current_company).present?%> <%= link_to "いいねを取り消す",product_like_path(@product.id, @product.liked_by(current_company)),method: :DELETE,remote: true, class: "loved hide-text"%> <% else %> <%= link_to "いいね",product_likes_path(@product),method: :POST,remote: true, class: "love hide-text"%> <% end %> </div> <% if @product.college == current_college %> <%= link_to("編集","/products/#{@product.id}/edit") %> <%= link_to("削除",@product,{method: "delete"}) %> <% end %> <br><br> <p><%= @product.content %></p> </div> </div> </div>
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。