Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Specify inverse_of on associations #127

Open
scottohara opened this issue Jan 9, 2018 · 0 comments
Open

Specify inverse_of on associations #127

scottohara opened this issue Jan 9, 2018 · 0 comments

Comments

@scottohara
Copy link
Owner

[email protected] introduced a new Rails/InverseOf cop (enabled by default).

The cop requires all has_one/has_many <=> belongs_to associations where Rails can't automatically determine the inverse relationship (such as in the presence of a class_name: or foreign_key: attribute) to explicitly specify the inverse relationship using inverse_of:.

This caused a number of offences, and when trying to add the missing inverse_of: attributes, a number of problems were encountered (below), so this cop has been locally disabled for now.

If we can resolve these issues, the cop can be reenabled (preferred).

Issues:

  • Account model defines an optional self-referential related_account association as follows:
belongs_to :related_account, class_name: 'Account', foreign_key: 'related_account_id', autosave: true, optional: true

There is no inverse has_one association defined, so it is currently unclear if there should be one.

  • Category model has a parent/child association as follows:
belongs_to :parent, class_name: 'Category', foreign_key: 'parent_id', optional: true
has_many :children, -> { order :name }, class_name: 'Category', foreign_key: 'parent_id', dependent: :destroy

Adding inverse_of: :children and inverse_of: :parent (respectively) caused a Stack level too deep error when trying to run the test suite.

  • TransactionCategory model has an association back to the base Transaction model as follows:
belongs_to :trx, foreign_key: 'transaction_id', class_name: 'Transaction'

But as only some transaction types are categorisable (e.g. BasicTransaction, Subtransaction), adding inverse_of: :transaction_category can't work as there's no Transaction.transaction_category association.

This may require using polymorphic: true and as:, e.g.

# basic_transaction.rb
has_one :transaction_category, foreign_key: 'transaction_id', dependent: :destroy, as: :categorisable_transaction

# transaction_category.rb 
belongs_to :categorisable_transaction, foreign_key: 'transaction_id', class_name: 'Transaction', polymorphic: true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant