错误:未定义的方法`[]'为零:类

时间:2014-07-30 14:43:00

标签: ruby-on-rails ruby

错误说有一个:"未定义的方法[]" 我的问题只是如何解决错误

我的user.rb文件,其中错误显示错误,我认为错误是

def your_questions(params)
    questions.paginate(page: params[:page], order: 'created_at DESC', per_page: 3)
end

我的问题控制器a.k.a app / controllers / questions_controller.rb

    class QuestionsController < ApplicationController
    before_filter :auth, only: [:create, :your_questions, :edit, :update]

  # def index
  #     @question = Question.new
  #   @questions = Question.unsolved(params)
  # end

  def self.unsolved(params)
    order('created_at DESC').where(solved: false).paginate(page: params[:page],per_page: 3)
  end

  def create
    @question = current_user.questions.build(params[:question])
    if @question.save
        flash[:success] = 'Your question has been posted!'
        redirect_to @question
    else
      @questions = Question.unsolved(params)
        render 'index'
    end
  end

  def new
       @question = Question.new
  end

  def show
    # raise FOO
    puts params
    @question = Question.find(params[:id])
    @answer = Answer.new
  end

  def your_questions
    @questions = current_user.your_questions(params[:id])
  end

  def edit
    @question = current_user.questions.find(params[:id])
  end

  def update
    @question = current_user.questions.find(params[:id])

    if @question.update_attributes(params[:question])
      flash[:success] = 'Your question has been updated!'
      redirect_to @question
    else
      render 'edit'
    end
  end

  def search
    @questions = Question.search(params)
  end
end

2 个答案:

答案 0 :(得分:1)

您将params[:id]传递给your_questions方法,而期望params。我要做的是:

def your_questions(page)
  questions.paginate(page: page, order: 'created_at DESC', per_page: 3)
end

这是因为此方法不需要知道您的整个params哈希值。然后,您只需使用params[:page]

调用此方法
current_user.your_questions(params[:page])

答案 1 :(得分:0)

当您在控制器中调用id时,您只会传递your_questions。不过,您尝试从:page

获取密钥id (string)

只需在您的控制器your_questions

中进行以下更改即可
@questions = current_user.your_questions(params[:page])

user.rb中,只使用page代替params[:page]

def your_questions(page)
    questions.paginate(page: page, order: 'created_at DESC', per_page: 3)
end