Mykhailo Rybak
Mykhailo Rybak

Reputation: 173

Understending STI and Polymorphic associations in rails

According to this answer i'm trying to inplement STI and Polymorphic associations together, my code:

class Post < ActiveRecord::Base
  belongs_to :content, :polymorphic => true
end

class Topic < Post #ActiveRecord::Base
  has_one :post, :as => :content, :dependent => :destroy
end

class Tutorial < Post #ActiveRecord::Base
  has_one :post, :as => :content, :dependent => :destroy
end

In post table i have columns content_id, content_type and in tables Topic, Tutorial column body

How can i create (in irb) new Tutorial or Topic ?

i tried Post.topics.new(..., :content => {body: 'my_text'})

but get an error

Upvotes: 0

Views: 202

Answers (1)

Mandeep
Mandeep

Reputation: 9173

well first of all i can't see STI here as you are inheriting from ActiveRecord in each model and secondly you are creating new topic but your syntax is wrong. Each Topic has one post and each post belongs to a Topic, so you should do something like Topic.post.build(params) to create a post and if you want to create a topic then Post.topic.build(prams)

Upvotes: 0

Related Questions