是否可以创建一个代表两个不同对象的模型? 例如:
I have a blog, on which, I will publish articles on pure text and screencasts with only video.
考虑到这一点:
我只想获取所有帖子 => @posts = Posts.all
我只想获取所有截屏视频=> @posts = Screencasts.all
我只想获取所有文章 => @posts = Articles.all
在 View 中我想知道这篇文章是哪个类
<% if @posts.first is article %>
do something
<% else %>
do something else
<% end %>
如果这不可能,我该怎么做呢?
最佳答案
您可以使用单表继承来实现此目的,但我不确定这是最佳解决方案。
您将拥有一个具有常用列的 Post 模型;正文、文本和截屏视频的 screencast_url 或类似内容。现在,通过将“类型”列添加为字符串,奇迹发生了。 Rails 将使用它来跟踪继承的模型。
然后您可以让两个模型都继承自 Post。
class Post < ActiveRecord::Base
end
class Screencast < Post
end
class Article < Post
end
现在您的代码示例应该按照您希望的方式工作。您可以在此 Rails API page 上找到有关 STI 的更多信息
你的循环可能是这样的:
<% @posts.each do |post| %>
<% if post.class == Article %>
do something
<% elsif post.class == Screencast %>
do something else
<% end %>
<% end %>
关于ruby-on-rails - Rails 中 1 个模型的 2 个用户定义类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6651686/