Class: RuboCop::Cop::Appdev::ExplicitAssociationOptions

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/appdev/explicit_association_options.rb

Overview

Requires explicit options on ActiveRecord associations so students see the column and class being wired up, rather than relying on Rails’ pluralization magic.

  • ‘belongs_to`, `has_one`, `has_many` (without `:through`) must pass `:class_name` and `:foreign_key`.

  • ‘has_many :through` and `has_one :through` must pass `:class_name`, `:source`, and `:through`.

  • ‘has_and_belongs_to_many` is banned entirely; use `has_many :through` instead.

Examples:

# bad
belongs_to :user
has_many :reviews
has_many :reviewers, :through => :reviews
has_and_belongs_to_many :tags

# good
belongs_to(:user, { :class_name => "User", :foreign_key => "user_id" })
has_many(:reviews, { :class_name => "Review", :foreign_key => "place_id" })
has_many(:reviewers, { :through => :reviews, :source => :reviewer, :class_name => "User" })

Constant Summary collapse

MSG_ONE_TO_N =
"`%<method>s(:%<name>s, ...)` requires `:class_name` and `:foreign_key`."
MSG_THROUGH =
"`%<method>s :through` requires `:class_name`, `:source`, and `:through`."
MSG_HABTM =
"`has_and_belongs_to_many` is not taught; use `has_many :through` instead."
RESTRICT_ON_SEND =
[
  :belongs_to,
  :has_one,
  :has_many,
  :has_and_belongs_to_many
].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/rubocop/cop/appdev/explicit_association_options.rb', line 38

def on_send(node)
  return if node.receiver
  return unless inside_class_or_module?(node)

  case node.method_name
  when :has_and_belongs_to_many
    add_offense(node, message: MSG_HABTM)
  else
    check_association(node)
  end
end