@814hiros

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

RubyonRails お気に入り機能追加について

Q&A

Closed

解決したいこと

ここに解決したい内容を記載してください。
Ruby on Railsで投稿に対してお気に入り機能を追加したいですが、以下のようなエラーが発生いたしました。
解決方法をご教授いただけますと幸いです。

よろしくお願いいたします。

発生している問題・エラー

ActiveRecord::RecordNotFound in FavoritesController#create
Couldn't find Micropost with 'id'=
Extracted source (around line #6):
4
5
6
7
8
9


  def create
    micropost = Micropost.find(params[:micropost_id])
    current_user.favorite(user)
    flash[:success] = 'お気に入りしました。'
    redirect_to micropost

または、問題・エラーが起きている画像をここにドラッグアンドドロップ。

該当するソースコード

favorites_controller.rb

class FavoritesController < ApplicationController

  before_action :require_user_logged_in

  def create
    micropost = Micropost.find(params[:micropost_id])
    current_user.favorite(user)
    flash[:success] = 'お気に入りしました。'
    redirect_to micropost
  end

  def destroy
    micropost = Micropost.find(params[:micropost_id])
    current_user.unfavorite(user)
    flash[:success] = 'お気に入りを解除しました。'
    redirect_to micropost
  end
end

-----------------------------------------------------------------------
microposts/models/user.rb

class User < ApplicationRecord
  before_save { self.email.downcase! }
  validates :name, presence: true, length: { maximum: 50 }
  validates :email, presence: true, length: { maximum: 255 },
                    format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i },
                    uniqueness: { case_sensitive: false }
  has_secure_password

  has_many :microposts
  has_many :relationships
  has_many :followings, through: :relationships, source: :follow
  has_many :reverses_of_relationship, class_name: 'Relationship', foreign_key: 'follow_id'
  has_many :followers, through: :reverses_of_relationship, source: :user
  has_many :favorites
  has_many :favorites, through: :favorites, source: :micropost
  has_many :reverses_of_favorite, class_name: 'Favorite', foreign_key: 'micropost_id'

  def follow(other_user)
    unless self == other_user
      self.relationships.find_or_create_by(follow_id: other_user.id)
    end
  end

  def unfollow(other_user)
    relationship = self.relationships.find_by(follow_id: other_user.id)
    relationship.destroy if relationship
  end

  def following?(other_user)
    self.followings.include?(other_user)
  end

  def feed_microposts
    Micropost.where(user_id: self.following_ids + [self.id])
  end


  def like
  unless self == other_micropost
      self.favorites.find_or_create_by(micropost_id: other_user.id)
  end
  end

  def unlike
    favorite = self.favorite.find_by(micropost_id: other_user.id)
    favorite.destroy if favorite
  end

  def favorite?(other_user)
    self.microposts.include?(other_user)
  end



end
0 likes

1Answer

Your answer might help someone💌