Polymorphic Wiring in Rails 4
I would like to run this past prior to implementing this.
I have Users and Groups , both of which can post Messages , and both of them can receive Messages ,
I think I need 2 polymorphic association in the Posts model:
posted and on the wall (posted shows model can create messages, wall art models can receive messages)
Thus, both users and groups must:
has_many :posts, :as => :posted
has_many :posts, :as => :wall
and the message should have
belongs_to :posted, :polymorphic => true
belongs_to :wall, :polymorphic => true
Also, should you use the "capable" convention, which I think has to do with Rails polymorphism? Simple and Walled It seems more readable to have User.wall for their wall and User.posted for recording their own posts. (Could I even change the wall to receive?)
thank
source to share
Poloymorphic
I think by nature you get "Polymorphic Association" :
It is designed to provide the ability to associate different models with one model; for example if you have 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
-
Individual table inheritance
You are trying to link the same model multiple times to the same model. While this is fine, I would assume you are actually 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 do the following:
@user = User.find 1
@user.wall_posts.each do |post|
post.name
end
source to share