Ruby on Rails - How to join two tables?

一曲冷凌霜 提交于 2019-12-03 10:08:11

1) ActiveRecord is going to map your query results to objects not arbitrary returned rows, so because you based the query creation off of the Subject class it is looking at your resulting rows and figures out that it is only referring to 1 unique Subject object, so returns just that single Subject instance.

2) The column data is there, but you are working against what ActiveRecord wants to give you, which is objects. If you would rather have Pages returned, then you need to base the creation of the query on the Page class.

3) You didn't save the results of adding the join(:pages)... back into the subject variable. If you did:

subject = subject.joins(:pages).where(['pages.name LIKE ?', '%Division'])

You would get the full query when running subject.to_sql

4) To get page objects you can do something like this, notice that we are basing it off of the Page class:

pages = Page.joins(:subject).where(['subjects.name = ? AND subjects.level = ? AND pages.name LIKE ?', 'Math', 2, '%Division'])

Then to access the subject name from there for the first Page object returned:

pages[0].subject.name

Which because you have the join in the first, won't result in another SQL query. Hope this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!