babie
babie

Reputation: 1447

How to create Post model with 2 model User/Admin rails?

I have 2 models (not STI) User and Admin. Now I want to create blog post (Post model) with both User and Admin. Is it impossible? Or any solution exists?

I tried some solution as:

Anyone have experiences or suggestion for this problem? It is appreciated.

Upvotes: 0

Views: 213

Answers (1)

MattwalOlaide
MattwalOlaide

Reputation: 71

Maybe a polymorphic model would be good?

Post could belong to an association that relates it to other models(in this case User and Admin). Maybe call it postable - or something better.

class Post < ApplicationRecord
 belongs_to :postable, polymorphic: true
end

class User < ApplicationRecord
 has_many :posts, as: :postable
end

class Admin < ApplicationRecord
 has_many :posts, as: :postable
end

You can look here for more info.

Upvotes: 2

Related Questions