Topic: New to rails, trying to filter

So I am brand new to rails, and programming, and am trying to setup a filter that will have 2 options.

in my controller, I've got:

 def index
    @expenses = Expense.filter(params[:category_id],[:who_id]) 

in my model I have

 def self.filter(category_id, who_id)
    if category_id.present? or who_id.present?
      return Expense.where(:category_id => category_id, :who_id => who_id)
    else
      return Expense.all
   end
 end

and in my view I've got:

<% @expenses.each do |expense| %>

  
  <tr>
    <td><%= link_to expense.category.name, expenses_path(:category_id=>expense.category_id) %></td>
    <td><%= link_to expense.who.name, expenses_path(:who_id=>expense.who_id) %></td>

When I go to my index, there are no entries, and when I add an entry and go back to my index, the entry doesn't exist.

Any ideas?

Re: New to rails, trying to filter

Hello fufaso,

You wrote
@expenses = Expense.filter(params[:category_id],[:who_id])
but it should be
@expenses = Expense.filter(params[:category_id],params[:who_id])

Also in your filter function you run "Expense.where(:category_id => category_id, :who_id => who_id)" which will return entries with corresponding category_id AND who_id, whereas in your condition "category_id.present? or who_id.present?" you use OR. What you want is probably something like:

 def self.filter(category_id, who_id)
    if category_id.present? and who_id.present?
      return Expense.where(:category_id => category_id, :who_id => who_id)
    elsif category_id.present?
      return Expense.where(:category_id => category_id)
    elsif who_id.present?
      return Expense.where(:category_id => who_id)
    else
      return Expense.all
   end
 end

Try to run your filter method from your console to check if it is working as you want at least in the model context.


Hope that helps,
Florent

Re: New to rails, trying to filter

Thanks great thanks Florent!