0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

エラー発生 NoMethodError in QuestionsController#new (解決済み)

Posted at

はじめに

今まで動いたのにトップページに質問相談検索機能を実装したら突然質問相談投稿ができなくなり以下エラーが表示。

undefined method move_to_index' for #<QuestionsController:0x00000000025c60>
Extracted source (around line #400): 
398  def make_lambda 
399  lambda do |target, value, &block| 
400  target.send(@method_name, &block) 
401  target.send(@method_name, &block) 
402   end 
403  end

どうやら検索機能を実装中にmove_to_indexの定義を消してしまったようだ。
以下訂正。

class QuestionsController < ApplicationController
  before_action :set_question, only: [:show]
  before_action :move_to_index, except: [:index, :show, :search]

  def index
    @questions = Question.all
  end

  def new
    @question = Question.new
  end

  def create
    @question = current_user.questions.build(question_params)
    if @question.save
      redirect_to @question, notice: '質問が作成されました。'
    else
      render :new
    end
  end

  def show
    @questions_answers = @question.questions_answers.includes(:user)
    @questions_answer = QuestionsAnswer.new
  end

  def search
    @questions = Question.search(params[:keyword]) # 検索処理  
    if @questions.count == 1
      redirect_to question_path(@questions.first) # 検索結果が1件ならそのページに遷移
    elsif @questions.empty?
      redirect_to questions_path, alert: '該当する質問は見つかりませんでした。' # 検索結果が0件ならメッセージを表示
    else
      render :search # 複数件ヒットの場合はそのままリスト表示
    end
  end

  private

  def set_question
    @question = Question.find(params[:id])
  end

  def move_to_index    # ココ追記。ログインしていない場合、トップページへリダイレクト
    unless user_signed_in?
      redirect_to root_path, alert: "ログインが必要です。"
    end
  end

  def question_params
    params.require(:question).permit(:symptoms, :progress, :medicine, :hospital, :habit,
                                      :favorite_food, :favorite_place, :image, :pet_id)
  end
end

おわりに

いろいろ機能を追加実装していくと前後のつながりが分断されてしまう事があるので(特にマイグレートは親子の順番で動かなくなったりするので)気を付けよう!!!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?