class RuboCop::Cop::Rails::RedundantForeignKey
end
belongs_to :author, foreign_key: ‘user_id’
class Comment
end
has_many :comments
class Post
# good
end
belongs_to :post, foreign_key: ‘post_id’
class Comment
end
has_many :comments, foreign_key: ‘post_id’
class Post
# bad
@example
is redundant.
Detects cases where the ‘:foreign_key` option on associations
def default_foreign_key(node, association_type, association_name, options)
def default_foreign_key(node, association_type, association_name, options) if association_type == :belongs_to "#{association_name}_id" elsif (as = find_as_option(options)) "#{as}_id" else node.parent_module_name&.foreign_key end end
def find_as_option(options)
def find_as_option(options) options.pairs.find do |pair| pair.key.sym_type? && pair.key.value == :as end&.value&.value end
def on_send(node)
def on_send(node) association_with_foreign_key(node) do |type, name, options, foreign_key_pair, foreign_key| if redundant?(node, type, name, options, foreign_key) add_offense(foreign_key_pair) do |corrector| range = range_with_surrounding_space(foreign_key_pair.source_range, side: :left) range = range_with_surrounding_comma(range, :left) corrector.remove(range) end end end end
def redundant?(node, association_type, association_name, options, foreign_key)
def redundant?(node, association_type, association_name, options, foreign_key) foreign_key.to_s == default_foreign_key(node, association_type, association_name, options) end