Rails 3查找has_many中的所有记录:通过以前的has_many没有碰撞

时间:2011-08-05 17:03:14

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

我有以下型号:

class User < ActiveRecord::Base
  has_many :books, :dependent => :destroy
  has_many :favorites
  has_many :books, :through => :favorites
end

class Favorite < ActiveRecord::Base
  belongs_to :book
  belongs_to :user

  validates :user_id, :book_id, :presence => true
end

class Book < ActiveRecord::Base
  belongs_to :user
  belongs_to :favorite
end

这个想法是用户可以拥有一本书并从另一个用户添加一本书作为收藏。在rails console中,我尝试了User.find(1).favorites.books但得到了NoMethodError:未定义的方法books'. And user.books`仅返回该用户拥有的书籍

在这种情况下,有没有办法检索属于用户最喜欢的所有书籍?

1 个答案:

答案 0 :(得分:4)

您非常接近,但您不应该有两个名称books的关联。尝试这样的事情:

class User < ActiveRecord::Base
  has_many :books, :dependent => :destroy
  has_many :favorites
  has_many :favorite_books, :through => :favorites, :source => :book
end

然后您的查询就是User.find(1).favorites_books