やりたいこと
現在、Q&Aサイトを作成しています。誰もが質問できるのですが、特定の専門家(adviser)が回答をできるように
デザインしています。
今回、friendly_id
を導入して、id
をslug
に変えて、URLに表示させるようにしたいと思っています。しかし、
このgemを導入したことで、幾つかの不具合が出てきました。
問題点
以下は、index.html.erbです。以下の画像をクリックしたら、questionのshow.html.erbに飛びます。
しかし、現在、それができないという問題が起きています。
ページ上部には、flash[:alert]が表示されています。
以下、関連するコードです。
Questions_controller.rb
このquestion/show.html.erbのページには、質問と回答、そして、回答にはコメントがつくようにデザインしています。
「The page you requested does not exist」がshowページで表示されているということは、
@question = Question.friendly.find(params[:question_id])の読み込みが失敗したという
ことだと思います。
どのように、改善すれば良いでしょうか?
def show if @answer @answer = @question.answers.find(params[:id]) @answer.question_id = @question.id @comment = @answer.comments.build @comment.answer_id = @answer.id else # @question = Question.find(params[:id]) @answer = @question.answers.build end # @answer.question_id = params[:id] end private def set_question @question = Question.friendly.find(params[:question_id]) rescue ActiveRecord::RecordNotFound flash[:alert] = "The page you requested does not exist." redirect_to questions_path end
Question.rb(model)
class Question < ApplicationRecord searchkick extend FriendlyId friendly_id :title, use: :slugged has_many :answers belongs_to :category validates :title, presence: {Title:'は、必須項目です。'} validates :content, presence: {message:'は、必須項目です。'} def normalize_friendly_id(value) value.to_s.parameterize.present? ? value.to_s.parameterize : value end def should_generate_new_friendly_id? title_changed? || super end end
View(Index.html.erb)は以下の通りです。
<% @questions.each do |question| %> <%= link_to question_path(question) do %> <div class="container-padding border-all-solid link"> <div class="row"> <div class="col-sm-12"> <h4 class="event-title"><span><%= fa_icon "question-circle lg",class: "fa-yellow" %></span><%= question.title %></h4> <hr class="border-b-dashed"> <div class="col-sm-6"> <span class="pull-left">投稿: <%= time_format(question.created_at) %></span> </div> <div class="col-sm-6"> <span class="pull-right">作成者:</span> </div> </div> </div> </div> <% end %> <% end %>
あなたの回答
tips
プレビュー