I have two models, users and notes, and in my project they have a double relationship, notes belongs to users (and vice versa) and notes has a polymorphic relationship that has users.
app/models/user.rb
class User < ApplicationRecord
has_many :notes # created by
has_many :notes, as: :noteable # note about
end
app/models/notes.rb
class Note < ApplicationRecord
belongs_to :user # created by
belongs_to :noteable, polymorphic: true # note about
end
How to differentiate between the notes that a user has created and the notes they have?
There are alternative way to?
app/models/user.rb
class User < ApplicationRecord
has_many :created_notes, class_name: 'Note' # created by
has_many :notes, as: :noteable # note about
end
I think that second User class should work - what’s going wrong when you’ve got that code?
We do almost this at $dayjob, in our case it’s model A has many Bs, but also belongs to a B, and our associations are:
class A < ApplicationRecord
belongs_to :b
has_one :owning_b, class_name: "B"
end
class B < ApplicationRecord
belongs_to :a, inverse_of: :owning_b
has_many :bs
end
Not sure if inverse_of will help your case, though.
In situations like this I move toward the prefix. However, to remove ambiguity when those relations get used, I add a prefix or suffix to both of them. In this case created_notes or written_notes. But instead of :notes I’d try to find a suitable prefix. In this case you could do notes_about and notes_written. Or something like that.
This way when you see its usage in other areas you don’t see user.notes and have to think about which one it is.