0

How to remove a column from the database and replace the column with a custom method so that I no need to change all the legacy code that is using the old column?

# Book.rb
# column available removed from the database

def available?
  # add custom available method here
  # will return true/false
end

The above code is fine and can be accessed with something like this, Book.first.available?. The question here is how to not change the query statement Book.where(available: true) but still get the same result? Is there a way to create a custom rails method and can be apply in query?

Dory
  • 95
  • 4
  • 19
  • 1
    I've googled similar case today, this answer may help you https://stackoverflow.com/a/39433171/3868595 – stolarz Jan 21 '22 at 15:59
  • 2
    What do you aim for to find a working replacement for `.where(available: true)` when available is replaced with a custom method? Or do you want to avoid the need to change `.where(available: true)` in the code? – spickermann Jan 21 '22 at 16:08
  • please add more information. `where(available: true)` does a database query, so if you remove the column, it won't work. – Blair Anderson Jan 21 '22 at 17:53
  • Theres no direct way of doing it through the query interface... meaning that you wont be able to achieve what you want with "where" method, or any other that creates a query. I don't believe theres a way to force a query to use instance methods instead of column value... you'll have to do it separately... one is evaluated in memory and the other goes directly to the database. – Gerardo S Jan 21 '22 at 18:29
  • Agree with @GerardoS, after some try and error, there is no direct way to patch it. Thank you for the suggestion spickermann and stolarz. – Dory Jan 23 '22 at 02:24

1 Answers1

1

From what I understood, I think this could work

def available_books
  all_available_books = Book.all
  all_available_books.select! { |book| book.available? }
end

def not_available_books
  all_not_available_books = Book.all
  all_not_available_books.select! { |book| !book.available? }
end