6

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?

1 Answer 1

21

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.