0

私はまだレールで学習曲線にあり、コーナーに戻ったようです。

シナリオ:

  • 人の詳細(id、first_name、last_name)を含む配列があり、配列の内容がビューに表示されます(テーブルとしてフォーマットされます)。

  • そのビューのコントローラーには、配列にフィルターを適用するメソッドがあります-その出力を制限します。

コントローラ

#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

意見

#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>

ルートファイル

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

  resources :persons do
    collection do
      get :filter_person
    end
  end

end

ビューのハイパーリンクを使用して、フィルターコントローラーメソッドをトリガーして配列をフィルター処理し、このフィルターを配置してビューを更新できるようにしたいと思います。私は何が欠けていますか?

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

フィルタ条件をラムダとしてformat.htmlレンダリングオプションに:locals参照として送信することにより、report_detailパーシャルをロードするときに、レンダリングされたデータを効果的に「フィルタリング」します。短期的には、既存のレイアウトを活用できるように、先頭のアンダースコア文字で部分を参照しています。将来的にはAJAXで部分ロードする可能性が高いです。

于 2012-11-20T15:34:57.623 に答える