Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a custom method in rails

I'm trying to figure out a good way to go about this.

Lets say I have a table that has posts, with titles, and different status IDs.

In my controller index, I have:

@posts = Post.all

Then in my model I have:

def check_status(posts)
  posts.each do |post|
    # logic here
  end
end

So in my controller I have:

   @posts.check_status(@posts)

but I'm getting the following error when loading the index:

undefined method check_status for <ActiveRecord::Relation:>

Any ideas?

like image 926
Elliot Avatar asked Feb 02 '11 15:02

Elliot


1 Answers

It should be a class method, prefixed with self.:

def self.check_status(posts)
  posts.each do |post|
    # logic here
  end
end

Then you call it like this:

Post.check_status(@posts)

You could also do something like this:

def check_status
  # post status checking, e.g.:  
  self.status == 'published'
end

Then you could call it on individual Post instances like this:

@posts = Post.all
@post.each do |post|
  if post.check_status
    # do something
  end
end
like image 183
Ashley Williams Avatar answered Oct 14 '22 14:10

Ashley Williams