简体   繁体   English

降低铁轨中的STI和多态关联

[英]Understending STI and Polymorphic associations in rails

According to this answer i'm trying to inplement STI and Polymorphic associations together, my code: 根据这个答案,我试图将STI和多态关联一起添加到我的代码中:

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 在发布表中,我的content_idcontent_type ,在表主题为Tutorial的列body

How can i create (in irb) new Tutorial or Topic ? 如何创建(在irb中)新教程或主题?

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

but get an error 但出现错误

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. 好吧,首先,我在这里看不到STI,因为您是从每个模型的ActiveRecord继承来的,其次您正在创建新主题,但是语法错误。 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) 每个主题都有一个帖子,每个帖子都属于一个主题,因此您应执行Topic.post.build(params)之类的操作来创建帖子,如果要创建主题,则应使用Post.topic.build(prams)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM