【问题标题】:Rails pass records from view to controllerRails 将记录从视图传递到控制器
【发布时间】:2015-09-15 16:57:52
【问题描述】:

在 Rails 3 应用程序中,我有一个包含搜索逻辑的视图。查看页面时,@events 包含要显示的记录。

查看代码:

<% @events.each do |event| %>
...

我在页面底部有一个按钮,用于使用 axlsx 创建 Excel 电子表格。我正在尝试将@events 传递回控制器。

这就是我正在尝试的按钮:

  <%= link_to "Excel", event_path("supportlog.xlsx", :events => @events), :class => 'btn btn-warning' %>

然后,在事件控制器中:

  def supportlog
    @events = params[:events]
    @events = Event.find(@events)

    respond_to do |format|
      format.xlsx
    end
  end

之前,我使用 params 传递一个 id - 这是我第一次尝试传递一个列表。

感谢您的帮助!

更新 1

我把控制器改成了这个:

  def index8
    @search = Event.search(params[:q])
    @events = @search.result
    respond_to do |format|
      format.html # index.html.erb
      format.xlsx
    end
  end

还有 index8 的视图按钮到这个:

<%= link_to "Excel", event_path("index8.xlsx"), :class => 'btn btn-warning' %>

但是,我需要将搜索参数返回到控制器中。

更新 2

这行得通:

  <%= link_to "Excel", event_path("index8.xlsx", :q => params[:q]), :class => 'btn btn-warning' %>

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    您可以将搜索参数传回控制器。或者更好的是,将导出部分作为搜索/索引的一部分(以不同的格式提供)。

    # search is part of the index action
    def index
      search_params = params[:search] || {}
      @events = Event.search(search_params)
      respond_to do |format|
        format.html {}
        format.json {}
        format.xlsx {}
      end
    end
    

    然后您可以在指定格式时使用搜索/索引 URL: = link_to 'Export', events_url(search: params[:search], format: :xlsx)

    HTTP 仅在视图/表单和服务器之间传递参数。 Rails 解析 HTTP 参数并构造 params 哈希,但不创建 AR 对象。

    【讨论】:

    • 使用不同格式的相同搜索效果很好!谢谢!
    • 我认为它有效。但是,它实际上是将所有事件都放入 XLSX。我会在我的问题中发布我所做的。
    • 如何通过按钮将搜索参数返回给控制器?
    • 这有效` params[:q]), :class=> 'btn btn-warning' %> `
    • 很高兴它成功了。检查你的 rake 路线。如果导出是索引的一部分(不是index8) - 您应该可以使用events_path(q: params[:q])
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    相关资源
    最近更新 更多