2016-08-28 26 views
1

我试图访问我的连接表数据,但可惜..Rails3中:使用连接表的数据

对于作者和图书,作者之间的示例关联有很多的书: 我使用join funtion加盟笔者表books表,以便使用该协会将努力进入笔者的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方法来完成呢?谢谢

回答

0

您需要添加

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

所以,你的查询变得

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