0

我有一个部分视图,如下所示:

# my_controller/my_view
The value of the parameter is <%= @parameter %>
<%= render :partial "my_contoller/my_partial", locals: {internal_param: @parameter_for_partial %>

#my_controller/my_partial
<div>
  The value of the internal parameter is <%= internal_param %><br />
  <%= link_to "Link", {:partial_url_param => internal_param + 1} %>
</div>

控制器操作采用 URL 参数:

def class MyControllerController < ApplicationController
  def my_action
    @parameter = params[:parent_view_url_param]
    @parameter_for_partial = params[:partial_url_param]
  end
end

现在,当我转到 时/my_controller/my_view?parent_view_url_param=1&partial_url_param=2,我得到一个如下所示的页面:

The value of the parameter is 1
<div>
  The value of the internal parameter is 2<br />
  <a href="/my_controller/my_view?partial_url_param=3">Link</a>
</div>

我希望链接指向/my_controller/my_view?parent_view_url_param=1&partial_url_param=3,原始链接中的所有 URL 参数都相同,除了部分直接覆盖的参数。此外,如果我添加更多参数,我希望部分中的链接也保留这些参数,而不需要我对部分进行任何更改。

在 Rails 4 中有没有办法做到这一点?

4

2 回答 2

1

怎么样

=link_to 'Link', params.merge(partial_url_param: internal_param + 1)
于 2013-07-28T21:48:52.573 回答
0

使用 bgates 回答中的方法,我创建了这个辅助方法并将其放入application_helper.rb

  # Creates a link back to the current view, keeping all of
  # the URL parameters the same except some that you
  # change. Also strips out some URL parameters that can
  # have implications for the app's security.
  #
  # Input params:
  # link_name: The text to show for the link
  # original_params: The params hash available to the view
  # params_to_change: A hash in the format of
  #   orignal_params that indicates which URL parameters
  #   to change, and what to change them to
  # html_options (optional): The HTML options to apply
  #   to the link
  #
  # Output: The HTML for a link back to the view with some
  #   of the URL parameters changed, as specified by
  #   the params_to_change hash
  def link_to_with_same_params(link_name, original_params, params_to_change, html_options = {})
    send_params = original_params.deep_dup
    send_params.delete :authenticity_token
    send_params.delete :commit
    send_params.merge! params_to_change
    return link_to link_name, send_params, html_options
  end

这允许我在示例视图中执行此操作:

#my_controller/my_partial
<div>
  The value of the internal parameter is <%= internal_param %><br />
  <%= link_to_with_same_params "Link", params, {:partial_url_param => internal_param + 1} %>
</div>
于 2013-07-28T22:33:18.883 回答