kaminariを仕様していて特定のtagのitemを並べたいと考えています。
class TagController < ApplicationController def show @tag = Tag.find_by(id: params[:id]) tag_maps = TagMap.where(tag_id: params[:id]) @posts = Post.where(post_id: tag_maps.post_id).page(params[:page]).per(10).order('updated_at DESC') @description = @tag.tag_des end end
tagmapを中間に挟んでいてTagMap.where(tag_id: params[:id])でurlのtag_idからtagmap(tag_idとpost_idが一緒に格納されているrable)をwhereで検索。そのtagページに該当するpostをwhereで更に並べたいのですが下記のエラーが出ます
kaminariで抽出するpostに条件をつけたい場合、どうすればいいんでしょうか?
class TagMap < ApplicationRecord belongs_to :post belongs_to :tag validates :post_id,presence:true validates :tag_id,presence:true end
class Post < ApplicationRecord has_many :tag_maps, dependent: :destroy has_many :tags, through: :tag_maps def save_posts(savepost_tags) current_tags = self.tags.pluck(:name) unless self.tags.nil? old_tags = current_tags - savepost_tags new_tags = savepost_tags - current_tags # Destroy old taggings: old_tags.each do |old_name| self.tags.delete Tag.find_by(name:old_name) end # Create new taggings: new_tags.each do |new_name| post_tag = Tag.find_or_create_by(name:new_name) self.tags << post_tag end end end
class Tag < ApplicationRecord validates :name,presence:true,length:{maximum:50} has_many :posts, through: :tag_maps has_many :tag_maps, dependent: :destroy end
回答1件
あなたの回答
tips
プレビュー