Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphic Posting in Rails 4

I would like to run this past SO before implementing this.

I have Users and Groups, both of which can create Posts and both of which can receive Posts.

I'm thinking I need 2 polymorphic association on the Posts model like this:

posted and wall (posted shows a model can create posts, wall shows models can receive posts)

So both User and Group should:

has_many :posts, :as => :posted
has_many :posts, :as => :wall

and Post should have

belongs_to :posted, :polymorphic => true
belongs_to :wall, :polymorphic => true

Also, should I be using the "able" convention I seem to see with Rails polymorphism? Postable and Wallable It seems more readable to have User.wall for their wall and User.posted for a record of their own posts. ( I might even change wall to recieved? )

Thanks

like image 667
David Sigley Avatar asked Mar 24 '26 13:03

David Sigley


1 Answers

Poloymorphic

I think by its nature, you're getting the Polymorphic association confused:

enter image description here

It's meant to provide the ability to associate different models to a single model; for example if you had the following:

#app/models/user.rb
Class User < ActiveRecord::Base
   has_many :tables, as: :bookable
end

#app/models/admin.rb
Class Admin < ActiveRecord::Base
   has_many :parties, as: :bookable
end

#app/models/restaurant.rb
Class Restaurant < ActiveRecord::Base
   belongs_to :bookable, polymorphic: true
end

--

Single Table Inheritance

You're trying to associate the same model multiple times from a single model. Whilst this is okay, I would surmise that you're really looking for an STI:

#app/models/user.rb
Class User < ActiveRecord::Base
   has_many :wall_posts, class_name: "User::WallPost"
   has_many :posts, class_name: "User::Post"
end

#app/models/post.rb
Class Post < ActiveRecord::Base
   belongs_to :user
end

#app/models/user/wall_post.rb
Class User::WallPost < Post
end

#app/models/user/post.rb
Class User::Post < Post
end

This will allow you to perform the following:

@user = User.find 1
@user.wall_posts.each do |post|
   post.name
end
like image 125
Richard Peck Avatar answered Mar 27 '26 08:03

Richard Peck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!