##閲覧履歴の表示が上手く出来ない。
現在小説サイトの真似をし練習中です。閲覧履歴を見れると良いと思い。
https://qiita.com/solare_tech/items/3cad7ada6c14a00ee15c
こちらのサイトを参考にして現在作っています。
####テーブル
・novel_lists
・users
・browsing_histories
モデルの関係性は下記となります。
■class User < ApplicationRecord has_many :browsing_histories, dependent: :destroy ■class NovelList < ApplicationRecord has_many :browsing_histories, dependent: :destroy ■class BrowsingHistory < ApplicationRecord belongs_to :user belongs_to :novel_list
###表示したいページ
novel_list_historyというページを別で作り、こちらに閲覧履歴一覧を表示したいと思ってます。 novel_listsの閲覧履歴全てなので、collectionで良いと思いcollectionとしています。 resources :novel_lists, only: [:index, :show, :new, :create, :edit, :update, :destroy] do collection do get :novel_list_history end
###コントローラ
class NovelListsController < ApplicationController def show @novel_list = NovelList.find(params[:id]) @novel_posts = @novel_list.novel_posts #ここから閲覧履歴を保存するコード new_history = @novel_list.browsing_histories.new new_history.user_id = current_user.id #if文追加、ログイン中のユーザー(current_user)の閲覧履歴(browsing_histories)の中で記事ID(article_id)が #URLに入力されているID(params[:id])と同じものがすでに存在しているか?(exists?) if current_user.browsing_histories.exists?(novel_list_id: "#{params[:id]}") old_history = current_user.browsing_histories.find_by(novel_list_id: "#{params[:id]}") old_history.destroy end new_history.save #ここから同一ユーザーの閲覧履歴の件数が上限を超えたときの処理と上限設定 histories_stock_limit = 10 histories = current_user.browsing_histories.all if histories.count > histories_stock_limit histories[0].destroy end end
####showに保存する処理を書きました。
続いて、novel_list_historyメソッドを作り、こちらで全てのデータを取得し。
def novel_list_history #閲覧履歴 @history = BrowsingHistory.all end
novel_lists/novel_list_histry.html.erb <% @history.each do |history| %> <%= history.novel_list.title %> <% end %> ここまでは表示に成功しています。 きちんとタイトルが表示されました。 リンクにしたいので、 novel_list GET /novel_lists/:id(.:format) こちらへのpathを書きます。 <% @history.each do |history| %> <%= link_to history.novel_list.title, novel_lost_path(history) %> <% end %> ここで、リンクへと飛ぶとエラーが出て表示さきへ飛べませんでした。
###エラー内容
ActiveRecord::RecordNotFound in NovelListsController#show
Couldn't find NovelList with 'id'=#BrowsingHistory::ActiveRecord_Relation:0x00007fa9209e4550
Extracted source (around line #9):
def show
@novel_list = NovelList.find(params[:id]) ←エラー箇所
@novel_posts = @novel_list.novel_posts
###試した事 BrowsingHistoryのidと関連させれていないのだと思い、 @novel_histry = @novel_list.browsing_historiesを追加。 変化はなく、エラーは変わりません。 @novel_list = NovelList.find(params[:id]) ←を追加し、pathに渡してるデータを@novel_listにしようとしたのですが、 こちらも、エラー変わらずでした。 その他関連しそうな部分を変えてみて様子をみているのですが、エラー内容は変わらず、苦戦しております。 わかる方いらっしゃいましたら、よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー