对发布的链接使用 Rails link_to

我有一个链接,我需要提交一个帖子请求与。通常,我会使用 jQuery 并防止链接的默认行为,然后向目标提交表单。这似乎是 Rails 应该能够帮助我解决的问题。果然,link_to方法有一个指定 POSThttp 方法的选项:

link_to "Profile", 'http://example.com/profile', method: :post

可以,但我还需要添加两个参数。我试过:

link_to "Profile", 'http://example.com/profile', method: post, param1: 'value1', param2: 'value2'

它只是将这些参数添加到 <a> HTML 元素中,但是在单击链接时没有提交这些参数:

<a rel="nofollow" param1="value1" param2="value2" data-method="post" href="http://example.com/profile">Profile</a>

有没有使用 link_to或任何其他 Rails 方法对参数执行 POST 请求的方法?我使用的是 Rails 3.2.9。

106310 次浏览

The short answer is that if what you mean by "parameters" is form fields, then you simply can't do this (at least not in a straightforward way that I can see). You should instead use a form with a submit button, styled to look like a link (if that's what you want it to look like).

If on the other hand you had meant query parameters, then this would work:

link_to "Profile", profile_path(@profile.id, param1: 'value1', param2: 'value2'), method: :post

You can encode parameters in the URL this way :

link_to "Profile", 'http://example.com/profile?' + {param1: 'value1', param2: 'value2'}.to_param, method: :post

If it does not fit your needs you are better use a form than a link_to.

In order to POST data, you need a form. However, you don't need a submit button. If you want this to look like a link for some reason, you can actually make it a link that submits the form via JavaScript. In the example below, the POST resource is just a REST action that does not require any fields so there are no form input controls. If you wanted to post some data, just put hidden input fields in the form.

<%= form_tag('http://something_postable', :method => :post, :class => 'internal') %></form>
<%= link_to_function('Label for Link', 'previous("form").submit()', :title => 'Hover text for link') %>

The form is assigned a class so you can style it or hide it via CSS (e.g. 'display: inline')

The parameters and the http method should be together {param1: 'value1', param2: 'value2', :method: :post}

<%= link_to "Profile", profile_path(@profile), {param1: 'value1', param2: 'value2', method: :post} %>

Note that if the user has JS disabled or you have removed the unobtrusive JS libraries that come by default, link_to will be silently submitted via a GET request.

In general, I am not very fond of having links that perform POST requests. I think that's the role of a form and a button.

Thus, an easy (and safer) alternative is to use the Rails button_to helper:

button_to 'Profile', profile_path(@profile, param1: 'value1', param2: 'value2')

button_to also supports the method option but as it defaults to post so I've just omitted it.

For Rails 7 with Turbo

link_to "Profile", profile_path(@profile), data: { turbo_method: "post" }