0

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

Community
  • 1
  • 1
Mykhailo Rybak
  • 163
  • 1
  • 2
  • 9

1 Answers1

0

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)

Mandeep
  • 9,093
  • 2
  • 26
  • 36
  • Update my question. Can you write full ActiveRecord create(build) query. cos i try and still shouldn't. – Mykhailo Rybak Oct 12 '13 at 18:38
  • Post.topics.build(title: 'title', content: {body: 'body'}) – Mykhailo Rybak Oct 12 '13 at 18:56
  • Check my answer again! Each post belongs to a topic so why are you writing Post.topics.build(). You should instead write Post.topic.build(). If there were a situation say each Post has many Topics, in that case you would do something like Post.topics.build() – Mandeep Oct 12 '13 at 19:07