2

我有一个索引视图,它变得有点笨重,所以我将所有数据库查询移到演示器中以尝试清理。

但是,将 params[:something] 与任何查询一起使用会使演示者错误:

undefined local variable or method params for QuestionPresenter:0x007fd6d569c158

我尝试将参数移动到应用程序控制器和模型中的辅助方法中,但没有成功。

我怎样才能让演示者可以使用这些参数?还是演示者不打算处理这些参数?

老问题_controller.rb

def index       
   if params[:tag]
      @questions = @question.tagged_with(params[:tag]).paginate(page: params[:page], per_page: 20)
    elsif params[:search]
      @questions = @question.paginate(page: params[:page], per_page: 20).search(params[:search])
    else
      @newest = @questions.newest.paginate(page: params[:page], per_page: 2)
      @unanswered = @question.unanswered.paginate(page: params[:page], per_page: 2).search(params[:search])
      @votes = @question.by_votes.paginate(page: params[:page], per_page: 2).search(params[:search])
  end 
end

QuestionsController.rb(新索引操作)

def index
  @presenter = QuestionPresenter.new
end

question_presenter.rb

class QuestionPresenter
  def initialize
    @questions = Question
    @tags = Tag
  end

  def questions
    @questions.paginate(page: params[:page], per_page: 20).search(params[:search])
  end

  def tags
   @tags.joins(:taggings).select('tags.*, count(tag_id) as "tag_count"').group(:tag_id).order(' tag_count desc')
  end

  def tagged_questions
    @questions.tagged_with(params[:tag])
  end

  def newest
    @questions.newest.paginate(page: params[:page], per_page: 20)
  end

  def unanswered
    @questions.unanswered.paginate(page: params[:page], per_page: 20)
  end

  def votes
    @questions.by_votes.paginate(page: params[:page], per_page: 20)
  end
end

index.html.erb

<%= render partial: "questions/tag_cloud", locals: {tags: @presenter.tags} %>

<% if params[:search] %> 
  <%= render partial: "questions/questions", locals: {questions: @presenter.questions} %>
<% elsif params[:tag] %>
  <%= render partial: "questions/questions", locals: {questions: @presenter.tagged_questions}%>
<% else %>
  <%= render partial: "questions/tabbed_index", locals: {questions: @presenter.newest, unanswered: @presenter.unanswered, votes: @presenter.votes} %>
<% end %>
4

2 回答 2

6

您必须将参数哈希从控制器传递到您的 QuestionPresenter:

QuestionsController.rb(新索引操作)

def index
  @presenter = QuestionPresenter.new(params)
end

question_presenter.rb

class QuestionPresenter
  def initialize(params = {})
    @questions = Question
    @tags = Tag
    @params = params
  end

  def params
    @params
  end

  ...

end
于 2013-06-25T17:08:35.357 回答
4

params变量只能从控制器或视图访问。

您必须将其传递给QuestionPresenter才能访问它。例如,您可以将 is 传递给QuestionPresenter#new方法,以便在方法中获取它,initialize然后可以将其保存到实例变量中,并在类中的所有位置@params替换为.QuestionPresenterparams@params

于 2013-06-25T17:04:18.417 回答