What’s the best way of searching across multiple active record models without using something like sphinx or solr?
What’s the best way of searching across multiple active record models without using something
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The simplest solution is to inherit models from the one and to store it in one table. However it’s very bad if you have an existent schema or if models differs much.
Another (and i think, much better) solution (if your database allow it) – to use UNION in your SQL to get results from multiple tables. In this case you should use
find_by_sql.For example, if you have
PostandQuestionmodels and want to list both in one list (and filter them by some conditions, possible) you should:Add field
typeto each table with default value matching model name. For example:Query both models as following:
Using
typefield Rails will distinguish different models and return list of both Post and Question, so you may search (or paginate) for both.