# Model finder with parameters

**URL:** <https://www.ruby-forum.com/t/model-finder-with-parameters/121629>\
**Category:** Rails\
**Created:** [November 29, 2007, 2:39pm UTC](https://www.ruby-forum.com/t/model-finder-with-parameters/121629 "2007-11-29T14:39:27Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![axplains](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/a183cd/32.png) [@axplains](https://www.ruby-forum.com/u/axplains)\
**Post date:** [November 29, 2007, 2:39pm UTC](https://www.ruby-forum.com/t/model-finder-with-parameters/121629/1 "2007-11-29T14:39:27Z")

</div>

Hi everyone,

I would like to refactor my finders in order to put query logic in the  
model.

In a view (contracts/list.rhml), I would have “sidebar” links to select  
contracts “by category” or “by customer”:

[code=]\<%# CATEGORIES %\>  
\<%# CREATES LINKS OF THIS TYPE: “/contract/list?category\_id=1” %\>

\<% categories = Category.find :all %\>  
\<% for category in categories %\>  
\<%= link\_to category.name, { :controller =\> “contract”,  
:action =\> “list”,  
:category\_id =\> category.id } %\>  
\<% end %\>

\<%# CUSTOMERS %\>  
\<% customers = Customer.find :all -%\>  
\<% for customer in customers %\>  
\<%= link\_to customer.name, { :controller =\> “contract”,  
:action =\> “list”,  
:customer\_id =\> customer.id } %\>  
\<% end %\>

…

TO DISPLAY THE FILTERED CONTRACTS WHAT SHOULD GO IN “params[…]”?

\<%= render :partial =\> “contract”, :collection =\>  
Contract.find\_contracts(params[…] -%\>[/code]  
The parameter is passed to the “find\_contracts” method of the “contract”  
model by a link of this kind: “/contract/list?category\_id=1”, in order  
to filter the contracts by the chosen category (or customer).

What I don’t get, is the syntax needed to read the parameters, the way  
to pass them without screwing up if a NIL is encountered, and leaving  
the “find\_contracts” method as flexible as possible.

Pseudo code to go in the model:

[code=]  
class Contract \< ActiveRecord::Base  
…  
def self.find\_contracts(\*args)  
cat = params[:category\_id]  
cust = params[:customer\_id]  
find\_contracts = Contract.find(:all,  
:conditions =\> [ “category\_id = ? AND  
customer\_id = ?”, cat, cust ]

end  
end[/code]  
I don’t get the correct syntax of it, and of the parameters.  
Moreover, I don’t know how to handle and evaluate empty (or nil)  
parameters.

Any help please?  
Thanks a lot in advance.

Axplains
