Rails: one-dimensional inheritance and find (: all) in parent

I understand how STI works because I am talking about the Post model, which contains forum posts and several subscriptions of 'commonUserPost' and 'adminUserPost', etc.

Now I want to define the same method in each of the subscriptions, but the method will do something different in each case, for example

class Post < ActiveRecord::Base
end

class AdminUserPost < Post
  def background_color
    'rockstar red'
  end
end

class OrdinaryUserPost < Post
  def background_color
    'pale blue'
  end
end

(yes, this is a stupid example). Now in my thread controller I am doing Post.find (: all) and it gives me a list of messages that I need to display, but they are Post objects, not AdminUserPost or OrdinaryUserPost - so I can’t just get my background_color method! I would need to find each type of user message separately ...

In any case, I can do:

Post.find(:all)

AdminUserPost OrdinaryUserPost Post?

"" Post AdminUserPost OrdinaryUserPost, ?

EDIT:

, , , Post "type". - , "post_type", :

self.inheritance_column = 'post_type'

(AdminUserPost OrdinaryUserPost ) (Post).

,

.

+3
3

, (). AdminUserPosts OrdinaryUserPosts "", , , .

+7

, , , Post "type". - , "post_type", :

self.inheritance_column = 'post_type'

(AdminUserPost OrdinaryUserPost ) (Post).

+1

Post.find(: ) , Post, AdminUserPost. , AdminUserPost :

AdminUserPost.find(:all)

, , Post.find(: all).

, named_scope :

# in model
Class Post << ActiveRecord::Base
  named_scope :admin_posts, :conditions => {:owner == 'admin'}
  named_scope :ordinary_user_posts, :condition => {:owner != 'admin'}
end

# in controller
@posts = Post.admin_posts # returns admin posts

# or
@posts = AdminUserPost.admin_posts # returns admin posts in AdminUserPost class 

, , .

Here you can find out more about these areas: http://railscasts.com/episodes/108-named-scope

EDIT:

Sorry, I'm new to the Rails community, and I haven't heard about STI before. dbarker is right, I tried, and it works the way you wanted.

-2
source

Source: https://habr.com/ru/post/1706146/


All Articles