· 2 min read

Screencast: Ransack

Downloads in verschiedenen Formaten:

mp4 m4v webm ogg

Resourcen:

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: <%= f.sort_fields do |s| %> <%= s.sort_select %> <% end %>
<%= f.submit “Search” %>
<% end %>

<% @products.each do |product| %> <% end %>
<%= 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) %>
\[/html\]

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

Sort: <%= f.sort_fields do |s| %> <%= s.sort_select %> <% end %>
<%= f.submit “Search” %>
<% end %> [/html]

products/_condition_fields.html.erb

[html]

<%= f.attribute\_fields do |a| %> <%= a.attribute\_select associations: \[:category\] %> <% end %> <%= f.predicate\_select %> <%= f.value\_fields do |v| %> <%= v.text\_field :value %> <% end %> <%= link\_to "remove", '#', class: "remove\_fields" %>
\[/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]

Back to Blog