【发布时间】:2017-04-27 23:39:48
【问题描述】:
我已经尝试了 2 天的解决方案,但仍然没有任何结果。
我有一个名为 Course 的模型,它具有以下列:
create_table :courses do |c|
c.integer :member_limit
c.string :color
c.float :rating
c.timestamps
end
我还有一个 Content 模型,其中包含 Course 受益的列,但也受益于我数据库中的其他模型,例如:
create_table :contents do |c|
c.references :contentable, polymorphic: true, index: true
c.string :title
c.text :description
c.text :script
c.string :cover
c.string :media_type
...
c.integer :creator_id, index: true, foreign_key: :user_id
end
我无法设置Course < Content,因为我会丢失Course 内部拥有的列,例如member_limit 等等,所以我选择了Polymorphic。但是,我想避免必须调用 course.content.title 并只写 course.title 但也以相同的方式访问 course.member_limit 并使用 course.save 保存这两个字段。
您推荐的最佳方法是什么?
当前结构。
课程:
class Course < ApplicationRecord
has_one :content, as: :contentable, dependent: :destroy
after_initialize :init
def init
if self.new_record?
self.content ||= build_content
end
end
end
内容:
class Content < ApplicationRecord
belongs_to :creator, optional: true, class_name: 'User'
end
【问题讨论】:
标签: inheritance methods polymorphism associations polymorphic-associations