Elliot
Elliot

Reputation: 13845

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?

Upvotes: 6

Views: 11633

Answers (1)

Ashley Williams
Ashley Williams

Reputation: 6840

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

Upvotes: 21

Related Questions