我有以下型号:
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` 仅返回该用户拥有的书籍
在这种情况下有没有办法检索属于用户最喜欢的所有书籍?
最佳答案
你们非常接近,但你们不应该有两个名为 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
关于ruby-on-rails - Rails 3 查找 has_many :through without collision from previous has_many 中的所有记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6959952/