多对多关系并加入rails 3

时间:2015-03-20 09:47:25

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2

我有以下三种模式

class Rating < ActiveRecord::Base
  belongs_to :user
  belongs_to :book
end

class User < ActiveRecord::Base
  attr_accessible :name, :dob, :mobile
  has_many :books, :through => 'ratings'
end

class Book < ActiveRecord::Base
  attr_accessible :book_name, :author, :pages
  has_many :users, :through => 'ratings'
end

现在我必须找到每本书中与相应用户相关的所有“book_name”并将其存储在数组中。

这是代码

@book_names = []
@books = Rating.find(:all, 'user_id = ?', current_user.id)
@books.each do |book|
  book_info = Book.find(book.id)
  @book_names << book_info.book_name
end

是否有相同或联接方法的其他方法。

1 个答案:

答案 0 :(得分:0)

是的,有简单的方法可以做到这一点。尝试

@book_names= current_user.books.map(&:book_name)