【问题标题】:rails model different post typesrails 对不同的柱子类型进行建模
【发布时间】:2015-03-18 00:20:59
【问题描述】:

我想为不同的帖子类型建模

ImagePostVideoPostTextPost。它们都有不同的内容

我打算使用 post has_many 多态,但 rails 不支持它

以前的 stackoverflow 帖子将我指向 has_many_polymorphs gem,但已弃用

我需要能够发布不同类型的帖子并在一个实例中检索它们,将它们显示在一个提要上 例如

@posts.each do .. 
  if type == video ... 
  elseif type == image ....

我是 Rails 新手,所以感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails rails-models


    【解决方案1】:

    使用Post模型的单表继承

     class class Post  < ActiveRecord::Base
      .....
     end
    

    而不是将这个 Post 模型继承到这些模型中。

    class VideoPost < Post
    
    end
    
    class ImagePost < Post
    end
    

    在迁移时,您需要为不同类型的帖子创建一个类型列。详情看这个blog post

    【讨论】:

      【解决方案2】:

      考虑执行以下操作

      class Post  < ActiveRecord::Base
          # Create the an association table and add additional info on the association table, description, etc etc.
          has_many :images, through: image_posts
          has_many :image_posts
      end
      
      class Image < ActiveRecord::Base
         # Image specific
      end
      

      这样做,@post.image_posts.count > 0 表示有多个 image_posts。

      或者你也可以通过多态关系来达到目的:

      class VideoPost < ActiveRecord::Base
        belongs_to :postable, polymorphic: true
      end
      
      class ImagePost < ActiveRecord::Base
        belongs_to :postable, polymorphic: true
      end
      
      class Feed < ActiveRecord::Base
        has_many :posts, as: :postable
      end
      

      在这种情况下,@feed.posts.each 将检查 postable_type,它是模型类型。

      【讨论】:

      • 当帖子可以是图片、视频或文本时,我将如何检查它是什么类型?
      • 更新了答案。类型由模型定义。使用计数检查应该可以解决您的问题。
      • 一个不必添加提要模型。如问题中所述。您希望有一个供稿的帖子列表,因此添加了供稿模型以用于说明目的。
      • 我更愿意采用视频和图像分离模型的解决方案。因为通常这些资产元素可以包含在其他模型中。例如,用户类可能有个人资料照片的图像。类评论也可能有图像/视频。
      【解决方案3】:

      性传播感染是要走的路。我猜这三种类型的列至少应该相同或相似。所以单故事继承是最好的选择。

      【讨论】:

        猜你喜欢
        • 2018-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多