Curently I have this code in my controller:
# sort by letter or by cuisine and letter def by_letter if params[:c].nil? @restaurant_pages, @restaurants = paginate_collection Restaurant.find_by_letter(params[:letter], params[:sort]), :page => @params[:page] @cuisines = Cuisine.find_all else @restaurant_pages, @restaurants = paginate_collection Restaurant.find_by_cuisine_and_letter(params[:id], params[:letter], params[:sort]), :page => @params[:page] @cuisines = Cuisine.find_all end end
Which decides what to do based on a string that is passed as a parameter to the action. The model then has two methods corresponding to the if and else clauses:
# restaurants that begin with a number def self.find_by_number(sort) Restaurant.find(:all, :conditions => ["name REGEXP '^[0-9]'"], :order => (sort || "name")) end
# restaurants that belong to a specified cuisine and begin with a number def self.find_by_cuisine_and_number(cuisine, sort) Restaurant.find(:all, :conditions => ["name REGEXP '^[0-9]' AND cuisine_id = ?", cuisine ], :order => (sort || "name")) end
My question is would it be better to pass the string to the model and then have an if statement that decides what the condition should be? This would mean less code repitition as the two methods above would be one shorter method. Thanks for your help. Feel free to ask any questions regarding the application.