· 2 min read
Screencast: Ransack
Downloads in verschiedenen Formaten:
Resourcen:
- Ransack
- Ransack Demo
- Episode 196: Nested Model Form (revised)
- Episode 111: Advanced Search Form (revised)
Gemfile
[ruby]
gem ‘ransack’ [/ruby]
products_controller.rb
[ruby]
def index @search = Product.search(params[:q]) @products = @search.result end [/ruby]
products/index.html.erb
[html]
<%= search_form_for @search, url: search_products_path, method: :post do |f| %> <%= f.condition_fields do |c| %> <%= render “condition_fields”, f: c %> <% end %>
<%= link_to_add_fields “Add Conditions”, f, :condition %>
<%= sort\_link @search, :name, "Product Name" %> | <%= sort\_link @search, :released\_on, "Release Date" %> | <%= sort\_link @search, :price, "Price" %> |
---|---|---|
<%= link\_to(product.name, product) %> | <%= product.released\_on.strftime("%B %e, %Y") %> | <%= number\_to\_currency(product.price) %> |
config/routes.rb
[ruby]
resources :products do collection { post :search, to: ‘products#index’ } end [/ruby]
products_controller.rb
[ruby] def index @search = Product.search(params[:q]) @products = @search.result @search.build_condition if @search.conditions.empty? @search.build_sort if @search.sorts.empty? end [/ruby]
products/index.html.erb
[html] <%= search_form_for @search, url: search_products_path, method: :post do |f| %> <%= f.condition_fields do |c| %> <%= render “condition_fields”, f: c %> <% end %>
<%= link_to_add_fields “Add Conditions”, f, :condition %>
products/_condition_fields.html.erb
[html]
application_helper.rb
[ruby]
def link_to_add_fields(name, f, type) new_object = f.object.send “build_#{type}” id = “new_#{type}” fields = f.send(”#{type}_fields”, new_object, child_index: id) do |builder| render(type.to_s + “_fields”, f: builder) end link_to(name, ’#’, class: “add_fields”, data: {id: id, fields: fields.gsub(“n”, "")}) end [/ruby]
products.js.coffee
[javascript] jQuery -> $(‘form’).on ‘click’, ‘.remove_fields’, (event) -> $(this).closest(‘.field’).remove() event.preventDefault()
$(‘form’).on ‘click’, ‘.add_fields’, (event) -> time = new Date().getTime() regexp = new RegExp($(this).data(‘id’), ‘g’) $(this).before($(this).data(‘fields’).replace(regexp, time)) event.preventDefault() [/javascript]