Rails记录没有关联

use*_*095 2 ruby activerecord ruby-on-rails polymorphic-associations

我正在寻找找到不属于用户的书籍的正确方法......以下是关联:

书 -

has_many :owns, :dependent => :destroy
Run Code Online (Sandbox Code Playgroud)

用户 -

has_many :owns, :dependent => :destroy
has_many :owned_books, :through => :owns, source: :book, :dependent => :destroy
Run Code Online (Sandbox Code Playgroud)

拥有 -

belongs_to :user
belongs_to :book
Run Code Online (Sandbox Code Playgroud)

我有不同标题的书籍视图(例如,Book.where(title => "Foo")或者Book.where(title => "Bar"),并且想要添加一个过滤器,用户只能看到他们不拥有该标题的书籍.对我而言,这应该是一个新的关联书模型,但我有点失落.

tad*_*man 7

如果您正在谈论排除用户拥有的那些:

Book.where.not(id: user.owned_book_ids)
Run Code Online (Sandbox Code Playgroud)

您可以通过附加它们来链接其他条件.