【问题标题】:Ruby on Rails: Pass Parameters to ViewRuby on Rails:将参数传递给视图
【发布时间】:2015-08-13 15:26:26
【问题描述】:

当用户在我的 Rails 应用程序中向 url /mobile 发出请求时,我希望将一个参数自动附加到请求后加载的 URL(类似于 /mobile?tree_width=5

我尝试了一些方法,但都没有奏效。

我得到的最接近的是我的控制器中的这个:

  def mobile
    respond_to do |format|
        format.html{
             # pass tree width here
             render mobile_project_steps_path(@project, :tree_width => @project.tree_width)
        }        
    end
  end

我收到了错误

Missing template /projects/8/steps/mobile?tree_width=5 

但我认为根据我的 rake 路线应该存在这条路径:

mobile_project_steps GET      /projects/:project_id/steps/mobile(.:format)                    steps#mobile

如何从控制器向 URL 添加参数?

【问题讨论】:

  • 您的意思是redirect_to 而不是render
  • @BroiSatse 如果我使用redirect_to,我会得到一个重定向循环
  • 因为需要条件,一会就写出答案。

标签: ruby-on-rails ruby routes params


【解决方案1】:

您需要检查参数是否丢失以及是否使用额外参数重定向到当前操作。我会在 before_action 中挤压它:

  before_action :check_tree_width, only: :mobile

  def mobile
    # Your actual logic
  end

  private

  def check_tree_width
    redirect_to(tree_width: @project.tree_width) unless params[:tree_width].present?
  end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 2012-06-26
    相关资源
    最近更新 更多