Home > Back-end >  Rails: How to use instance method in Active Record Query
Rails: How to use instance method in Active Record Query

Time:07-15

I am having a filter query which should return all the records where either

  1. attribute (column) "status" is not "done", or
  2. instance method "completeness_status" does not return "done"

The query is something like that: Studies.where("studies.status != ? OR studies.completeness_status != ?", "done", "done") but I am getting error that column completeness_status does not exist.

Unfortunately, the column status is not continuously updated, so I cannot use it only. Also, the instance method "completeness_status" is based on records from other tables. I try to add a scope to my model and use this instance method as scope but also I was not successful. Also, I tried to used it as class method but then I do not know how to call it from where clause.

def self.completeness_status(study)
 # code
end

or

def self.completeness_status_done?(study)
 # code return true or false
end

Any Idea how to solve that. Thanks.

CodePudding user response:

You cannot use instance methods inside your query. But if you like to check the condition of completeness for only one row, then you can use it as instance method:

first_study = Study.first
first_study.completeness_status_done?

Also, if you provide more information about what is going on inside your completeness_status_done? then maybe I can give you some ideas to use scopes.

https://guides.rubyonrails.org/active_record_querying.html

  • Related