繁体   English   中英

Rails 3从has_many中查找所有记录:直通之前的has_many

[英]Rails 3 Find all records from has_many :through without collision from previous has_many

我有以下型号:

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 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM