Rails 6 warning: Overwriting existing method <model_name>.fetched_state
Asked Answered
O

1

5

Rails 6.0.2.1 ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-linux]

my ArticleDir class has 2 scopes:

scope :active, -> { where(active: true).where(expired_on: nil) }
scope :fetched_state, -> { where(state: ArticleDir::FETCHED.to_s) }

and a function:

def article_engine_counts(keyword_reln = Keyword.active_keywords)
      joins(:keywords, :article_engine)
      .where(Keyword.contains(keyword_reln))
      .where(self.table[:active].eq(true))
      .group(:state, ArticleEngine.table[:name]).count
end

On running the function in rails console, I get:

irb(main):108:0> ArticleDir.article_engine_counts(keyword)

Creating scope :active. Overwriting existing method ArticleDir.active.

Creating scope :fetched_state. Overwriting existing method ArticleDir.fetched_state.

(1.7ms) SELECT COUNT(*) AS count_all, article_commons.state AS article_commons_state, sengines.name AS sengines_name FROM article_commons INNER JOIN directory_keywords ON directory_keywords.article_dir_id = article_commons.id INNER JOIN keywords ON keywords.id = directory_keywords.keyword_id INNER JOIN sengines ON sengines.id = article_commons.sengine_id AND sengines.type = 'ArticleEngine' WHERE article_commons.type = 'ArticleDir' AND keywords.id IN (1217) AND article_commons.active = TRUE GROUP BY article_commons.state, sengines.name

=> {["expired", "data..."]=>1, ["fetched", "data..."]=>83, ["sourced", " data..."]=>81}

I've seen one other reference to this issue: https://github.com/rails/rails/issues/31234 where it was suggested that the message related to overwriting a Kernel method.

I've checked the Kernel and no such methods exist on the Kernel in the first place to overwrite:

irb(main):002:0> Kernel.methods.grep(/active/)
=> []
irb(main):004:0> Kernel.methods.grep(/fetched_state/)
=> []

I am assuming that the message means what it seems to imply - arel / rails is somehow overwriting those two scopes on the model.

If so, why? and what do I do about it?

Outwash answered 5/4, 2020 at 14:5 Comment(0)
F
7

This can happen when you have something such as an enum that add scopes to the model.

If, in your model, you had an enum with :active as one of the values, e.g.:

enum status: [ :active, :archived ]

to go along with your explicit scope, you would see this warning.

Ferriter answered 19/7, 2020 at 5:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.