我有一个控制器querys
,其行为为send_file
。
querys_controller.rb
def send_file
send_data(params[data], :filename => "query.txt")
end
在html.erb中我有:
<%=link_to "send data", :controller=>"querys", :action=>"send_file", :data=>@mat, method: :post%>
通过单击“发送数据”,rails显示“Bad request”,因为@mat是一个二维数组,而且似乎我link_to无法发送这样的结构。如何将矩阵发送到控制器?
@mat:
[["1681", "", "02.05.1955"], ["1680", "", "02.03.1936"], ["1679", "", "26.11.1938"], ["1692", "", "15.05.1958"]]
答案 0 :(得分:1)
在生成html.erb的控制器方法中,将@mat实例存储在某处,并获取记录的ID。将此ID传递给link_to,并使用来自DB的此数据作为send_data调用的参数。
(小提示:实际上不使用ID,这不是安全的,而是使用随机值。或者甚至更好:如果可以将值附加到current_user,则根本不传递任何内容。)
您收到错误请求,因为Rails不了解您请求的格式。那是因为你自己组装了网址。使用像
这样的电话link_to "send file", send_file_querys_path(format: :txt)
甚至是
button_to ....
如果是POST操作。
您可以使用&#39; rake routes&#39;获取有效路线。这使您的应用程序更易于测试。
我希望我的回答可以帮助您重新编写代码。如果你正在做的是正确的方法,那么@m_x会给你正确的指针。
致以最诚挚的问候,
雨果
答案 1 :(得分:0)
when passing url arguments in the form of a hash, you should separate them from the rest of the arguments for link_to
:
<%
= link_to "send data",
{controller: "querys", action: "send_file", data: @mat},
method: :post
%>
However, this will pass the data as query parameters. If you really want to pass the data as POST parameters (for example, if @mat
contains a lot of data), you will have to use a form tag with a hidden field and a submit button.
IMO a more efficient approach would be to pass the parameters that were required to populate @mat
, repopulate the variable server-side and use it in send_file
.
The best practice in this regard is to leverage rails' format
capabilities, for example :
def some_action
@mat = populate_mat(params)
respond_to do |format|
format.html
format.txt do
send_data(@mat, :filename => "query.txt")
end
end
end
(note : for this to work, you will probably have to register the txt
mime type in config/initializers/mime_types.rb
)
then in some_action.html.erb
:
<% = link_to "send data", {format: :txt}, class: 'whatever' %>
This will will just add a .txt
extension at the end of the current url, which plays nicely with the REST paradigm (one endpoint per resource, with the extension indicating the desired representation).
You can also pass the format
option to any url helper, for example :
<%= link_to "root", root_path(format: :txt), class: 'whatever' %>
答案 2 :(得分:0)
试试这个:
link_to("Send data", send_file_querys_path(data: @mat), method: :post)