#4
Mar 12, 2007

Move Find into Model

Move a find into the model to clean up the controllers and remove duplication. Also see how you can call these custom find methods through an association.
Download (4.8 MB, 2:03)
alternative download for iPod & Apple TV (2.8 MB, 2:03)
# tasks_controller.rb
def index
  @tasks = Task.find_incomplete
end

# models/task.rb
def self.find_incomplete
  find_all_by_complete(false, :order => 'created_at DESC')
end

# projects_controller.rb
def show
  @project = Project.find(params[:id])
  @tasks = @project.tasks.find_incomplete
end

7 comments

James May 28, 2007 at 22:17

Very nice example, great work!


Lucky Sep 08, 2007 at 10:14

Hi Ryan,

On this topic "Move Find into Model", I have queries which I hope you could help to enlighten me:

I provide CRUD of books. First, user will have to select the action (i.e. C, R, U or D) from the menu. Then, a search screen is displayed for user to enter the book title/s which s/he would like to check.

The search string could contain more than one word, * (0 or more character wild card), ? (single character wild card) and so on.

In this case, should the formatting and validation of the search string be also embedded in the Book model, together with the Find in the Book model? If not, where should this be included?

Thank you for your help.


Ryan Bates Sep 11, 2007 at 08:11

@Lucky, yes, I would put the handling of the search wild cards into the model. That's logic that doesn't belong in the controller.


James Sep 22, 2007 at 16:09

I am curious about the self.find...

Why is it that this method requires "self." ?


James Sep 23, 2007 at 09:46

I found an answer to something that has been confounding me about the self. thing. I am learning about OO programming, so I admit that this may seem obvious to a lot of people. Please excuse my ignorance.

Here is a link regarding how this works.
http://wiki.rubyonrails.org/rails/pages/RubyHeadScratching

Thank you Ryan for all the excellent work in your railscasts. I really appreciate the patience and clear mindedness that you demonstrate in your screencasts. You express yourself as a joyful and brilliant person.


Juan Carlos Rodríguez Dec 06, 2007 at 23:36

Great job! Thanks


john May 01, 2008 at 03:29

i know this is wrong place to write this but i need a solution i want to know how mapping should be done mine case is " A has many B , A has many C, every B has some C which is added to above list which is related to A. so tell me the way to map them . i have mapped B and C to A

Add your comment:

(SKIP THIS ONE)

(required)

(not shown)


(required)

subscribe:
sponsored by:
if you want to help:
required:
Get Quicktime Player