Topic: Rails Beginner. I'm sure this code can be re-factored.

Well it does say beginners welcome in this forum smile So I thought I'd try asking some questions here. I've built a few Rails applications so far and although my understanding is improving, I'm aware that there are many places where my code could be improved. I don't have a user group or anything like that so I'd appreciate any help that anyone can offer here.

I often find myself writing something that works, but I'm left with the feeling that with a better knowledge of ruby I could have done something much more elegant. Here is such an example. It's a method which  takes an input from a search form where any combination of a number of options could have been submitted. I'd appreciate any comments or suggestions for improvements.

class ListController < ApplicationController
    @results = Product.find_with_product_finder(params, :order => 'category ASC', :limit => '20')
end

class Product < ActiveRecord::Base
    def self.find_with_product_finder(params, options={})
    orientation_scope(params[:orientation]) do
        property_scope("frame", params[:property][:frame]) do
          property_scope("door", params[:property][:door]) do
            attribute_scope("acoustic", params[:attribute][:acoustic_rating]) do
              attribute_scope("airtight", params[:attribute][:airtight]) do
                attribute_scope("fire", params[:attribute][:fire_rating]) do
                  self.find(:all, options)
                end
              end
            end
          end
        end
    end
  end

  private

  def self.orientation_scope(orientation)
    with_scope(:find => {:conditions => ['orientation = ? OR orientation = ?', orientation, 'both'], :include => [:category]}) do
      yield
    end
  end
 
  def self.property_scope(column, value)
    with_scope(:find => {:conditions => property_conditions(column, value)}) do
      yield
    end
  end
 
  def self.attribute_scope(column, value)
    with_scope(:find => {:conditions => attribute_conditions(column, value)}) do
      yield
    end
  end
 
  def self.attribute_conditions(column, value)
    if column != "airtight"
      column = "#{column}_rating"
    end
    if value == "1"
      conditions = "#{column} != 0"
    else
      conditons = "#{column} LIKE '%'"
    end
  end
 
  def self.property_conditions(column, value)
    if value == "0"
      conditions = "#{column} LIKE '%'"
    else
      conditions = "#{column} = '#{value}'"
    end
  end

end

Re: Rails Beginner. I'm sure this code can be re-factored.

Wow..some serious nesting going on there. You should really look into with_scope.

If that is too limited there is also a neat plugin called scope_out

If that tickles your fancy and by chance you are also paginating, check out this article by our very own Danger, who has extended the plugin brilliantly.