Creating a custom method in rails

I am trying to find a good way to do this.

Suppose I have a table in which there are posts with headers and different status identifiers.

In my controller index, I have:

@posts = Post.all

Then in my model I:

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

So, in my controller, I:

   @posts.check_status(@posts)

but when loading the index, the following error occurs:

undefined method check_status for <ActiveRecord::Relation:>

Any ideas?

+3
source share
1 answer

This should be a class method with a prefix 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 can also do something like this:

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

Then you can call it in separate instances Post, for example:

@posts = Post.all
@post.each do |post|
  if post.check_status
    # do something
  end
end
+17
source

Source: https://habr.com/ru/post/1789525/


All Articles