前提・実現したいこと
掲示板アプリを作成しています。
ユーザーが複数のトピックを持つ事ができて、それに対して投稿ができるといったものです。
トピックの詳細ページから投稿ができて、その投稿に対して「いいね機能」を実装しようとしているのですが、エラーが表示されてしまい、それが解決できないでいます。
実装の際に参考にした記事はこちらです。
https://qiita.com/nojinoji/items/2c66499848d882c31ffa
発生している問題・エラーメッセージ
ActionController::UrlGenerationError in Topics#show No route matches {:action=>"create", :controller=>"likes", :id=>"3", :topic_id=>#<Post id: nil, text: nil, image: nil, topic_id: nil, user_id: nil, created_at: nil, updated_at: nil>}, missing required keys: [:post_id], possible unmatched constraints: [:topic_id]
該当のソースコード
haml
1_like.html.haml 2 3- if current_user.already_liked?(@post) 4 = button_to 'いいねを取り消す', topic_post_like_path(@post), method: :delete 5- else 6 = button_to 'いいね', topic_post_likes_path(@post)
ruby
1class LikesController < ApplicationController 2 before_action :set_post, only: [:create, :destroy] 3 4 def create 5 @like = current_user.likes.create(post_id: params[:post_id]) 6 if @like.save 7 redirect_to topic_path(@topic) 8 end 9 end 10 11 def destroy 12 @like = Like.find_by(post_id: params[:post_id], user_id: current_user.id) 13 if @like.destroy 14 redirect_to topic_path(@topic) 15 end 16 end 17 18 private 19 def set_post 20 @post = Post.find(params[:post_id]) 21 end 22end
ruby
1class TopicsController < ApplicationController 2 before_action :move_to_index, except: [:index] 3 before_action :set_topic, only: [:show, :edit, :update, :destroy] 4 5省略 6 7 def show 8 @category = Category.find(params[:id]) 9 @post = Post.new 10 @like = Like.new 11 @posts = @topic.posts 12 end 13 14 15 private 16 def topic_params 17 params.require(:topic).permit(:title, :introduction, :category_list).merge(user_id: current_user.id) 18 end 19 20 def set_topic 21 @topic = Topic.find(params[:id]) 22 end 23end
ruby
1class Like < ApplicationRecord 2 belongs_to :post 3 belongs_to :user 4 validates_uniqueness_of :post_id, scope: :user_id 5end
ruby
1class User < ApplicationRecord 2 # Include default devise modules. Others available are: 3 # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable 4 devise :database_authenticatable, :registerable, 5 :recoverable, :rememberable, :validatable 6 7 has_many :topics, dependent: :destroy 8 9 has_many :posts, dependent: :destroy 10 has_many :likes, dependent: :destroy 11 has_many :like_posts, through: :likes, source: :post 12 13 validates :nickname, presence: true 14 15 16 def already_liked?(post) 17 self.likes.exists?(post_id: post.id) 18 end 19end
ruby
1class Post < ApplicationRecord 2 belongs_to :user 3 belongs_to :topic 4 has_many :likes 5 has_many :liked_users, through: :likes, source: :user 6 7 validates :text, presence: true 8end
試したこと
「いいね」ができる詳細ページに遷移ができないことや、エラー文からもアソシエーションが疑わしいのかなと思いましたが、いまいち原因がわかりませんでした・・・。
possible unmatched constraints
一致しない可能性のある制約という意味らしいので、整合性が取れていないということなのでしょうか?
補足情報(FW/ツールのバージョンなど)
rails (5.2.4.3)
あなたの回答
tips
プレビュー