Reputation: 510
We have models as below...
class Post
has_many: :comments, as: :commentable
end
class Media
has_many: :comments, as: :commentable
end
class Comment
belongs_to: :commentable, polymorphic: true
belongs_to: :post, foreign_key::post_id, foreign_type: 'Post'
end
Exampale
Post1 has Comment3 => {id: 3, text: "Some comment 3", commentable_id: 1, commentable_type: 'Post'}
Media2 has Comment4 => {id: 4, text: "Some comment 4", commentable_id: 2, commentable_type: 'Media'}
When I want to access Comment3.post it gives result as expected.
But When some how want access Comment4.post it brings an object from post table which has id = 2, but expected nil, coz Comment4 does not belongs to any post.
We can get from below method inside Comment model, but want as an association.
def post
self.commentable if self.commentable_type == 'Post'
end
Could not get what I expected.., Please help here...
Upvotes: 1
Views: 309
Reputation: 5734
I like your approach
def post
self.commentable if self.commentable_type == 'Post'
end
But if you really need it in the association way, then you can try with
belongs_to :post, foreign_key: :commentable_id, foreign_type: :commentable_type, polymorphic: true
OR
belongs_to :post, -> (record){ record.commentable_type == 'Post' ? joins(:comments).where(comments: {commentable_type: 'Post'}) : where("false") }, foreign_key: :commentable_id
Hope, it helps.
Upvotes: 2