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