Thursday, January 7, 2010

Ruby on Rails Fat model and skinny controller

Ruby on Rails controller actions should be very clear and should not contain more than two instance variables in an action. So almost write everything in model as the methods and call them in controller actions. I write a code below for how to done it to get related galleris.
#app/model/gallery.rb
class Gallery < ActiveRecord::Base

def self.get_related(galname)
related = find(:all, :conditions => ['name like ?', '%'+galname+'%'])
end
end

#app/controllers/galleries_controller.rb
class GalleriesController < ApplicationController
def show
@gallery = Gallery.find(params[:id])
@related = Gallery.get_related(@gallery.name)
end
end

#app/views/galleris/show.rhtml

Related Galleries


<% @related.each do |relate|%>
<% if (relate.id!=@gallery.id)%>


<%= link_to( relate.name , { :action=>'show', :id=>relate.id}) %>


<% end %>
<% end %>

1 comments:

sachinnaik said...

if you use named_scope for what you have done it will keep your code much cleaner.