0

The following gets me the results I want but I am trying to figure out if I could have done this with a join or includes instead.

@items = Item.find_by_sql("SELECT *
    FROM items_with_metadata
    FULL OUTER JOIN items ON items.id = items_with_metadata.item_id")

The result should be that I get all attributes from both tables and the attributes are null wherever the items_with_metadata did not match an item in the items table. ALSO, I do not have any associations between the two tables, the id of some items just happens to be in both tables

So for example if I have items table with

 id | name | active
------------------
123 |  a   |   0
456 |  b   |   1

and items_with_metadata has

color | usable | location | item_id
-----------------------------------
 red  |   yes  |   north  |  123

the result of the query will be

id  | name | active | color | usable | location | item_id
--------------------------------------------------------
123 |  a   |   0    |  red  |   yes  |   north  |  123
456 |  b   |   1    |       |        |          |

I was hoping there was a way to do this using ActiveRecord's joins or includes or any other ActiveRecord method that is not find_by_sql

4

1 回答 1

0

怎么样:

Item.joins('完全外连接 items_with_metadata ON items.id = items_with_metadata.item_id')

编辑:

您还可以使用:

@items = Item.includes(:items_with_metadata)

这将只返回 Item 模型,但也会将所有相关的 ItemWithMetadata 模型加载到内存中,这将使它们通过以下方式可用:

@items.first.items_with_metadata

最后一条语句不会导致数据库查询,而是从内存中加载项目元数据。

于 2012-09-11T17:59:52.513 回答