简体   繁体   English

Rails 中 1 个 model 的 2 个用户定义的类

[英]2 User-defined classes for 1 model in Rails

Is it possible to create one model that stands for two different objects?是否可以创建一个代表两个不同对象的 model ? for example:例如:

I have a blog, on which, I will publish articles on pure text and screencasts with only video.我有一个博客,我将在该博客上发表纯文本文章和仅包含视频的截屏视频。

With that in mind:考虑到这一点:

I want to get only all posts => @posts = Posts.all我只想获取所有帖子 => @posts = Posts.all
I want to get only all screencasts=> @posts = Screencasts.all我只想获取所有截屏视频=> @posts = Screencasts.all
and I want to get only all articles => @posts = Articles.all我只想获取所有文章 => @posts = Articles.all

And in the view I want to know which class is this post在视图中我想知道这篇文章是哪个 class

<% if @posts.first is article %>
  do something
<% else %>
  do something else
<% end %>

if this is not possible, how can I do something like that?如果这是不可能的,我该怎么做呢?

You could use Single Table Inheritance to achieve this but I'm not sure it's the best solution.您可以使用 Single Table Inheritance 来实现这一点,但我不确定它是否是最佳解决方案。

You would have a Post model which has the usual column;您将有一个 Post model ,它具有通常的列; body, text and a screencast_url or something similar for your screencast.正文、文本和 screencast_url 或您的截屏视频的类似内容。 Now the magic happens by also adding the "type" column as a string.现在神奇的发生是通过将“类型”列添加为字符串。 Rails will use this to keep track of the inherited model. Rails 将使用它来跟踪继承的 model。

You could then have both models inherit from Post.然后,您可以让两个模型都从 Post 继承。

class Post < ActiveRecord::Base
end

class Screencast < Post
end

class Article < Post
end

Now your code example should work the way you want it to.现在您的代码示例应该按照您希望的方式工作。 You can find more information about STI on this Rails API page您可以在此Rails API 页面上找到有关 STI 的更多信息

Your loop could be something like this:你的循环可能是这样的:

<% @posts.each do |post| %>
  <% if post.class == Article %>
    do something
  <% elsif post.class == Screencast %>
    do something else
  <% end %>
<% end %>

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

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