Ruby on Rails:将参数传递给视图

Ruby on Rails: Pass Parameters to View

当用户在我的 Rails 应用程序中向 url /mobile 发出请求时,我希望一个参数自动附加到 URL 之后加载的 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 routes应该存在这条路径:

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

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

您需要检查参数是否丢失,以及是否使用额外参数重定向到当前操作。我会用 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