Ruby on Rails: Way to test for ActiveRecord Where conditions without hitting database?
I am using Ruby on Rails 2.3.8. I have several User model objects stored in memory and several Where conditions that I want to check these against. Because all this data is stored in memory I want to avoid hitting the d开发者_StackOverflowatabase to perform these checks. Is there a way to check these models without hitting the database, i.e. some way to validate a SQL Where condition against an in-memory model object?
To make things more clear, if I were to actually pull the record from the database I would do something like this:
whereCondition = "name LIKE 'James Smith'"
User.find(:first, :conditions => [whereCondition])
I have several Users and several whereConditions available in memory, and what I'd really like to do is something like this:
someUser.meetsCondition?(whereCondition)
Which would return a boolean. Is there some way of doing this without writing my own SQL parser?
Thanks.
If the User is already in memory then doing something like the following shouldn't reload the object should it?
user.name =~ /James Smith/
There is no way to do this without parsing it yourself.
However, if you wanted to, you could create a sqlite in-memory database and load the records into it and then you could use your query. I don't know how practical this would be though - it's definitely too much work to be doing on a normal web request, and the cost of doing this could very well be more expensive than just running the query against your real database again anyways. You'll have to experiment.
No, there is no built-in mechanism to execute SQL logic against in-memory collections. You would have to write your own SQL parser to do what you are wanting.
Rails has caching settings that you can read about on the Rails Guide site. Some of those may suit what you're trying to accomplish.
You also may want to check out Memcached in conjunction with the cached_model gem. I generally use this and update the cached copy of the object in an after_save
model callback.
精彩评论