From 928e63f9659d0b0af5a07aaaa66c7c2e773a38fd Mon Sep 17 00:00:00 2001 From: Holger Frohloff Date: Sat, 6 Oct 2012 23:14:47 +0200 Subject: [PATCH] Added associations (has_many & belongs_to) to README commit 646784e84d007848203bf00d99e3f3d757586da1 Author: Holger Frohloff Date: Sat Oct 6 23:11:36 2012 +0200 Added attributes to model descriptions modified: README.md commit 60e62d1e847ebdb948e01f41997a91d768f99fbb Author: Holger Frohloff Date: Sat Oct 6 23:09:29 2012 +0200 Renamed @search object modified: README.md commit c547afaf0aaea3ec07a62298ba933a332bf01755 Author: Holger Frohloff Date: Sat Oct 6 23:06:19 2012 +0200 Added associations to README modified: README.md --- README.md | 52 +++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c17dc1e..b93cb43 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ If you're coming from MetaSearch, things to note: 1. The default param key for search params is now `:q`, instead of `:search`. This is primarily to shorten query strings, though advanced queries (below) will still - run afoul of URL length limits in most browsers and require a switch to HTTP + run afoul of URL length limits in most browsers and require a switch to HTTP POST requests. This key is [configurable](https://github.com/ernie/ransack/wiki/Configuration) 2. `form_for` is now `search_form_for`, and validates that a Ransack::Search object @@ -103,6 +103,56 @@ Once you've done so, you can make use of the helpers in Ransack::Helpers::FormBu construct much more complex search forms, such as the one on the [demo page](http://ransack-demo.heroku.com). +### has_many and belongs_to associations + +You can easily use Ransack to search in associated objects. + +Given you have these associations ... + + class Employee < ActiveRecord::Base + belongs_to :supervisor + + # has attribute last_name:string + end + + class Department < ActiveRecord::Base + has_many :supervisors + + # has attribute title:string + end + + class Supervisor < ActiveRecord::Base + belongs_to :department + has_many :employees + + # has attribute last_name:string + end + +... and a controller ... + + class SupervisorsController < ApplicationController + def index + @search = Supervisor.search(params[:q]) + @supervisors = @search.result(:distinct => true) + end + end + +... you might set up your form like this ... + + <%= search_form_for @search do |f| %> + <%= f.label :last_name_cont %> + <%= f.text_field :last_name_cont %> + + <%= f.label :department_title_cont %> + <%= f.text_field :department_title_cont %> + + <%= f.label :employees_last_name_cont %> + <%= f.text_field :employees_last_name_cont %> + + <%= f.submit "search" %> + <% end %> + + ## Contributions To support the project: