Rails3:使用 joined table 的数据

Rails3: Use joined table's data

我正在尝试访问我加入的 table 数据,但是唉..

比如作者和书籍的关联,作者有很多本书: 我正在使用 join 功能将作者 table 加入书籍 table 以访问作者的 author_name 属性

class Author < ActiveRecord::Base
  has_many :books

  attr_accessible :author_name
end

class Book < ActiveRecord::Base
  belongs_to :author
end

random_author = Author.first
books = random_author.books.where(id > 5).joins(:author) #this should make all author attributes available to each book, right?

book_1 = books.first
book_1.author_name
=> NoMethodError: undefined method `author_name' for #<Book:0x111111>

当然可以使用关联:book_1.author.author_name 但这将需要另一个查询,而这正是我要避免的。

我的意思是 joins 操作加入了作者的数据 - 一定有办法访问它吧?

p.s。我可以使用 includes 方法。并急切地加载作者数据,但由于我只需要一个属性 - 有没有办法只用 joins 方法来完成它?谢谢

您需要添加

.select('books.*, author.name AS author_name')

因此您的查询变为

books = random_author.books.where(id > 5).joins(:author).select('books.*, author.name AS author_name')