Fabián Contreras
Fabián Contreras

Reputation: 43

Can i have a model that belongs_to another model under two different names in rails?

That is, I have Attachment model that belongs_to User model, User has_many attachments. I want the User as well to have many Attachments under another name, Extras lets say.
So when I call User.attachments will bring me a group, but calling User.extras will bring another, of the same class.

I am sure there is a problem with my approach as I can not find anything similar in the guides.

#User model
class User < ApplicationRecord
 
  has_many :attachments, dependent: :destroy
  has_many :extras, class_name: "Attachment", dependent: :destroy #my guess

end

#Attachment model
Class Attachment < ApplicationRecord

  belongs_to :user, optional: true
  belongs_to :user, as: "Extra", optional: true #my guess

end

Upvotes: 0

Views: 43

Answers (2)

Les Nightingill
Les Nightingill

Reputation: 6154

You need a condition to distinguish attachments from extras, for example:

class User < ApplicationRecord
  has_many :attachments, -> { where(extra: false) }
  has_many :extras, -> {where(extra: true) }, class_name: "Attachment"
end

class Attachment < ApplicationRecord
  belongs_to :user
end

NB the second belongs_to in the Attachment class is not required.

Upvotes: 2

yeuem1vannam
yeuem1vannam

Reputation: 957

In order to distinguish 2 kinds of attachment, your Attachment model must have something for clarifying. Suppose you have a column named kind to do so:

class Attachment < ApplicationRecord
  enum kind: {
    attachment: 1,
    extra: 2
  }
  belongs_to :user, optional: true
end

By having this setup, you can make two has_many relations at User model using conditions for them:

class User < ApplicationRecord
  has_many :attachments, -> { where kind: Attachment.kinds[:attachment] }, dependent: :destroy
  has_many :extras, class_name: "Attachment", -> { where kind: Attachment.kinds[:extra] }, dependent: :destroy
end

P/S: You can use STI to distinguish between 2 kinds of attachment as well

Upvotes: 2

Related Questions