简体   繁体   中英

Ruby on Rails search for querying two tables

I want to build a search on my website that is similar to Facebook.

For example, entering a search phrase and returning results from multiple tables.

In turn, I have two tables on my website which include the following: Account and Posts. I want to make a search that returns results from both tables based on a search phrase.

I am confused on how to do this.

Can someone point me in the right direction please.

Thank you,

Brian

You can do a search on a joined field by doing a joins to join the second table. For example:

Account.where(:your_attribute => search_term).joins(:post).where("posts.some_attribute = ?", search_term_2)

Or if you're searching from the opposite direction:

Post.where(:some_attribute => search_term).joins(:accounts).where("accounts.your_attribute = ?", search_term_2)

If you want to do an or between the two tables, you can. Just modify the query a little:

Post.joins(:accounts).where("posts.attribute = ? or accounts.attribute = ?", search_term)

If I'm reading your post correctly, what you want to do is in a single search box, you want to search multiple tables and return multiple types of data. On Facebook, it returns people, apps, pages, etc. By doing a join, you are going to return Post with their associated users, however, this won't return Users that don't have any posts, and even if you did an "outer join" on the table, it wouldn't be scalable if you wanted to search additional models.

Your simplest solution without introducing more software in to the mix is to create a database view that maps the data to a structure where its more easily queryable. In Rails/Ruby, you would query that view like you would a normal database table.

A more complex solution would be to use a full text index such as Apache Solr and use a gem like acts_as_solr_reloaded to query the full text index. At the end of the day, this would be a more robust and scalable solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM