0

I'm still on the learning curve with rails, and seem to have backed myself into a corner.

Scenario:

  • There is an Array containing people details (id, first_name, last_name), and the Array contents are displayed in a View (formatted as a table).

  • There is a method in the Controller for that View which applies a filter to the array - limiting its output.

Controller

#person_controller.rb

require 'module_file'

class PersonController < ApplicationController
  include ModuleFile
  helper_method :build_list

  def index
  end

  def filter_person
    @filter_criteria = lambda { |person| person.id.nil? }
    redirect_to persons_path
  end
end

View

#index.html.erb

<%= link_to "Filter Report", :controller => :person, :action => :filter_person %>

<table>
  <% ModuleFile.build_list.individuals.find_all(&@filter_criteria).each do |person| %>
    <tr>
      <td><%= person.id %></td>
  <td><%= person.first_name %></td>
  <td><%= person.last_name %></td>
    </tr>
  <% end %>
</table>

Routes File

#/config/routes.rb
MyApplication::Application.routes.draw do

  resources :persons do
    collection do
      get :filter_person
    end
  end

end

I would like to be able to use a hyperlink on a View to trigger the filtering controller method to filter the Array, and then refresh the View with this filter in place. What am I missing?

4

2 回答 2

1

我曾经遇到过同样的问题并以这种方式处理它:

# my_model_controller
class MyModelController < ApplicationController
  # ...
  def query
    # Bring a json with the queried array of xxx
    render :json => MyModel.find_all {|i| i.attribute == params[:query]}
  end
end
//  my_model_script.js
$.get("/persons/query", {
  query: $query // query parameters
}, function(data) {
  console.log("Hey! Here's the queried array of persons: " + data.json + ".");
  // Do something with each person
});

这是我实现它的示例应用程序:https ://github.com/nicooga/Example-Padrino-Blog/blob/master/app/controllers/posts.rb 。这是一个 Synatra+Padrino 应用程序,但除了不存在routes.rb文件之外,它几乎是相同的东西。

编辑:如果您不想执行 AJAX,您可以使用 url 参数创建链接,例如:

= link_to 'Apply filter', "/MyModel?filter=true"

# MyModel_controller.rb
def method_blah
  apply_filter if params[:filter]
end
于 2012-11-17T00:06:20.293 回答
0

这是我最终使用的解决方案:

控制器文件

# person_controller.rb

require 'module_file'

class PersonController < ApplicationController
  include ModuleFile
  helper_method :build_list

  def index
  end

  def filter_person
    @filter_criteria = lambda { |person| person.id.nil? }
    respond_to do |format|
      format.html {render '_report_detail', :layouts => 'reports', :locals {:@filter_criteria => @filter_criteria } }
    end
  end
end

通过将我的过滤条件作为 lambda 发送到 format.html 渲染选项作为 :locals 引用,它在加载 report_detail 部分时有效地“过滤”渲染的数据。在短期内,我使用前导下划线字符引用部分,以便我可以利用现有布局。将来我很可能会使用 AJAX 进行部分负载。

于 2012-11-20T15:34:57.623 回答