【问题标题】:Render text with params使用参数渲染文本
【发布时间】:2014-05-10 10:35:07
【问题描述】:

我有一个超级简单的任务,不知道如何实现它。

主控制器如下所示:

class MainController < ApplicationController
  def index
    if render_text.include? "bar"
      render :text => render_text, params: { :bar => true } # http://localhost:3000/main/index?bar=true
    else
      render :text => render_text # http://localhost:3000/main/index
    end
  end

private
  def render_text
    output = Page.find(params[:id])
  end
end

根据数据库的输出,我想要么向 url 添加参数,要么只渲染文本而不需要任何额外的 url 参数。

所以网址最好是这样的:

http://localhost:3000/main/index?bar=true   

【问题讨论】:

  • output = Page.find(params[:id]) 这将如何给出字符串 bar 的结果? Page.find(params[:id]) 的结果是什么,我想这会将找到的具有指定 ID 的记录分配给输出,并且方法 render_text 也不会返回任何内容。让我知道。
  • @Dave,Page 类型的所有记录都作为字符串返回。假设这是一个带有一些随机单词的文本
  • 好的。方法 render_text 应该像这样返回输出 (return output = Page.find(params[:id])) 对吗?

标签: ruby-on-rails render


【解决方案1】:

据我所知,您的代码存在许多问题:

  1. 为什么要将参数传递给 url?
  2. 您不能在不创建新请求的情况下将参数传递给 URL(I.E 重定向)

首先,为什么要将参数传递给 URL? Rails 对sessions 有很好的支持,这使得在后端传递数据变得简单且安全。感谢您可能希望在地址栏中看到某些参数,但在这种情况下我不明白(需要更多上下文)

其次,您使用render :text 作为输出。为什么?

当 Rails 处理入站请求时,它会将您的用户带到特定的控制器操作。因此,如果您的 URL 如下:domain.com/users/2,您将访问users#show, id =&gt; 2 路由。当您在控制器中处理该路由时,输出将使用 url 中传递的数据(请求是一个操作)

您正尝试在同一操作中将参数附加到 url。这不起作用 - 您必须重定向到附加 bar 参数的新操作:

  #app/controllers/main_controller.rb
  def index
      bar = "true" if render_text.include? "bar"
      redirect_to main_index_path(bar: bar)
  end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 2012-11-12
    相关资源
    最近更新 更多