railsで非同期のいいね機能を実装しているのですがエラーが発生してしまい進めません。
どなたか解決策を教えていただけないでしょうか。
カウント機能も付けています。
エラー内容
NoMethodError (undefined method `like' for #<Recruitment:0x00007f8814676300> Did you mean? likes like?): app/controllers/likes_controller.rb:6:in `create'
コントローラー
class LikesController < ApplicationController def create @recruitment = Recruitment.find(params[:recruitment_id]) unless @recruitment.like?(current_user) @recruitment.like(current_user) @recruitment.reload respond_to do |format| format.html { redirect_to request.referrer || root_url } format.js end end end def destroy @recruitment = Like.find(params[:id]).recruitment if @recruitment.like?(current_user) @recruitment.unlike(current_user) @recruitment.reload respond_to do |format| format.html { redirect_to request.referrer || root_url } format.js end end end end
likeモデル
class Like < ApplicationRecord belongs_to :user belongs_to :recruitment counter_culture :recruitment validates :user_id, presence: true validates :recruitment_id, presence: true def like(user) likes.create(user_id: user.id) end # いいねを解除する def unlike(user) likes.find_by(user_id: user.id).destroy end end
recruitmentモデル
class Recruitment < ApplicationRecord belongs_to :user has_many :likes, dependent: :destroy has_many :like_users, through: :likes, source: :user def self.search(search) if search Recruitment.where('recruitment_type LIKE(?)', "%#{search}%") else Recruitment.all end end def like?(user) like_users.include?(user) end end
ビュー
- if recruitment.like?(current_user) = form_for(recruitment.likes.find_by(user_id: current_user.id), method: :delete, remote: true) do |f| = button_tag(class: "btn btn-default btn-xs") do = content_tag :span, "#{recruitment.likes_count}", class: "glyphicon glyphicon-heart" - else = form_for(recruitment.likes.build, remote: true) do |f| %div= hidden_field_tag :recruitment_id, recruitment.id = button_tag(class: "btn btn-default btn-xs") do = content_tag :span, "#{recruitment.likes_count}", class: "glyphicon glyphicon-heart-empty"
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。