rails:将2-d数组传递给link_to

时间:2015-06-15 12:46:45

标签: ruby-on-rails ruby multidimensional-array

我有一个控制器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"]]

3 个答案:

答案 0 :(得分:1)

@Tonja,对我来说,你在做什么似乎很奇怪。首先,您在某处生成一个数组,然后使用浏览器将其传递回您的应用程序。然后以文本格式将其发送回浏览器? 您不应将此数组传递给用户,而是将其保留在服务器上。只需将其存储在数据库中即可。仅在绝对必要时才将数据传递给用户。您当前的实现还会强制您对传递的数据进行一些检查。

在生成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)