简体   繁体   中英

2 User-defined classes for 1 model in Rails

Is it possible to create one model that stands for two different objects? 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
I want to get only all screencasts=> @posts = Screencasts.all
and I want to get only all articles => @posts = Articles.all

And in the view I want to know which class is this post

<% 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.

You would have a Post model which has the usual column; body, text and a screencast_url or something similar for your screencast. Now the magic happens by also adding the "type" column as a string. Rails will use this to keep track of the inherited model.

You could then have both models inherit from 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

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 %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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