gpt4 book ai didi

ruby-on-rails - Presenter 的未定义局部变量或方法 `params'

转载 作者:太空宇宙 更新时间:2023-11-03 17:11:19 24 4
gpt4 key购买 nike

我有一个索引 View ,它变得有点笨重,所以我将所有的数据库查询都移到了演示者中,以尝试清理一切。

但是,在任何查询中使用 params[:something] 会使演示者出错:

QuestionPresenter 的未定义局部变量或方法参数:0x007fd6d569c158

我曾尝试将参数移动到 applicationcontroller 和模型的辅助方法中,但没有成功。

如何让演示者可以使用这些参数?还是 Presenter 不打算处理此类参数?

旧的 question_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 %>

最佳答案

您必须将参数散列从 Controller 传递给您的 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

关于ruby-on-rails - Presenter 的未定义局部变量或方法 `params',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17303281/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com