简体   繁体   English

Rails:在单个查询中从联接表获取字段

[英]Rails : get fields from join tables in one single query

Starting with rails, i want to create a request with dynamic selection and dynamic sorting, like following examples (in SQL): 从rails开始,我想创建一个具有动态选择和动态排序的请求,例如以下示例(在SQL中):

    select * from books join authors on author_id = books.id 
    where books.title like '%something%'
    order by author.name, books.title

or 要么

    select * from books join authors on author_id = books.id 
    where books.title like '%something%'
    order by books.title, author.name

Author has_many books, book belongs to author. 作者has_many很多书,这本书属于作者。

I code this with two nested loops. 我用两个嵌套循环对此进行编码。 In the first case, Author (sorted by name) is read first then Book (sorted by title), in the second case, Book first then author. 在第一种情况下,首先阅读作者(按名称排序),然后阅读书(按标题排序),在第二种情况下,先阅读本书,然后阅读作者。 I can then print together books fields and authors fields. 然后,我可以将书本字段和作者字段一起打印。 The loops must reflect the hierarchy of sort fields. 循环必须反映排序字段的层次结构。

But many other fields exist, and dynamic selection/ordering may be any field(s). 但是还存在许多其他字段,并且动态选择/排序可以是任何字段。

Is there a way to write a single 'each' loop, where books fields and authors fields would be available together, like with above sql examples. 有没有一种方法可以编写单个“每个”循环,像上述sql示例一样,books字段和authors字段可以一起使用。 My problem is to get fields from several tables on one single line. 我的问题是从一行中的多个表中获取字段。

What would the 'find' request be? “查找”请求是什么?

Thanks for your help. 谢谢你的帮助。

Your basic query would be something like: 您的基本查询如下所示:

@books = Book.where("title LIKE ?", "%{something}%").joins(:author).order("author.name ASC, books.title ASC")

As for controlling the sorting, you can break that into scopes that get conditionally added depending on your params. 至于控制排序,您可以将其划分为可以根据参数有条件添加的范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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