Kazik February 2016

Can object have 2 parents in rails?

Hi I have a comment object, and I use polymorphic association, so it can belongs to many other objects. But I also want them to belong to users.

Now I can, call comment.comment_owner and I get the object that was commented by this comment.

As for the user I have a user_id field in the comment object, I pass the user id through the form. But when I try to get owner user by comment.user I get an error. Right now I`m getting user by User.find(comment.user_id). But this looks bad.

Is there a way to pass the user id. So I can get User owning a comment by comment.user

My associations:

class Comment < ActiveRecord::Base
  belongs_to :comment_owner, polymorphic: true
end

class User < ActiveRecord::Base
  has_many :comments, as: :comment_owner
end

class Posts < ActiveRecord::Base
  has_many :comments, as: :comment_owner
end

Answers


Oleander February 2016

Why not just

class Comment < ApplicationRecord
  belongs_to :user
end


MichaƂ Czapko February 2016

First of all, in my opinion comment_owner is not a good name for what you're designing here. Comment owner would suggest an ownership relation (rather a person or someone). I'd rather call it commentable as these object are being commented on.

If this relation is meant to be a polymorphic then you should have commentable_type and commentable_id (or comment_owner_type and comment_owner_id if you really prefer the original) as polymorphic => true expects to have those two fields (named as: relation_name_type and relation_name_id).

If you then have a Comment object you get the user commented by calling comment.commentable (or comment.comment_owner in case you decide to keep your naming).

[EDIT] As you said, you want to have two parents. If I get this right you just want to have two relations - this means that if you just modify your code to:

class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
  belongs_to :author, class_name: 'User'
end

class User < ActiveRecord::Base
  has_many :comments, as: :commentable
  has_many :notes, class_name: 'Comment'
end

class Post < ActiveRecord::Base
  has_many :comments, as: :commentable
end

You will have your polymorphic relation as well as the ownership.

Post Status

Asked in February 2016
Viewed 3,671 times
Voted 11
Answered 2 times

Search




Leave an answer