spicyShoyo
spicyShoyo

Reputation: 413

Rails 4 includes unscoping default scope of association

Say I have this setting:

In model Book:

default_scope -> { where(published: true) }

In model Author:

default_scope -> { where(english: true) }
scope :english_author_book, -> (book_ids) {includes(:book).where({ books: { id: book_ids } })}

I tried all kinds of stuff but I just can't remove the default scope of Book: 'positions'.'published' = 1 is always in the query

Is there a way to fix this? Thank you!

The association:

In model Book:

has_many :authors, dependent: :destroy, inverse_of: :book

Im model Author:

belongs_to :book, :inverse_of => :authors

Sorry about that the example seems unrealistic, but I can't post the full code here :/

Upvotes: 1

Views: 550

Answers (1)

chrismanderson
chrismanderson

Reputation: 4813

You can use unscoped to remove the default scope. Documentation available here.

Book.unscoped.english_author_book(ids)

However, I highly highly highly cannot stress enough highly recommend you do not use a default scope. They are incredibly inflexible as you have already found, tough to deal with, and almost always a bad idea.

Turn the default scope into a normal scope so you can do Book.published and your code will be much better for it.

Upvotes: 2

Related Questions