4

I have a model named "Post" with following attributes:

class Post < ActiveRecord::Base
  attr_accessible :content, :published_at, :status, :title, :type, :user_id
  has_many :entity_categories
  has_many :entity_pages
end

A post have type field that specifies type of post (e.g. Regular, News, ...).
And I want to use multiple controllers and views with this model (News should use different template and logic from Regular post).
For example, if type == regular it must uses controller named CommonPost and its templates.
How can I solve this problem?

pruzoth
  • 41
  • 1
  • 11
S.M.Mousavi
  • 5,013
  • 7
  • 44
  • 59
  • 2
    You don't want to create class RegularPost < Post and then the regular_posts_controller etc ? – oldergod Aug 13 '12 at 07:21
  • IMHO, you don't need different controllers. You just need to render different layouts/views conditionally. – Kulbir Saini Aug 13 '12 at 07:35
  • Something similar to this would be helpful for you. http://stackoverflow.com/questions/3025784/rails-layouts-per-action – Rahul Aug 13 '12 at 07:40
  • Thanks @oldergod. You gave me idea to right way. Please convert your comment as Answer and complete it. I created new classes on `models` section in my project and i inherited it from base model (RegularPost – S.M.Mousavi Aug 14 '12 at 01:43

2 Answers2

3
migration CreatePostTable

class Post < ActiveRecord::Base
  attr_accessible :content, :published_at, :status, :title, :type, :user_id
  has_many :entity_categories
  has_many :entity_pages
end

class RegularPost < Post
end

class SpecialPost < Post
end

In your DB, you only have a Post table and Rails will set automatically the type column to the right class.

Like you could do

puts RegularPost.new.type
# => "RegularPost"

then you create regular_posts_controller, spcial_posts_controller etc and you are good to go. Is it what you were looking for?

oldergod
  • 15,033
  • 7
  • 62
  • 88
1

If i am understanding you correctly, you can still use one controller, you just need different views. In your controller you can have your if type == regular then render commonpost.

You can put as much logic and code as you want in there but you can split and do different things in your Post controller based on what type is.

Hope this helps

Troy Cosentino
  • 4,658
  • 9
  • 37
  • 59
  • 1
    Thank you very much. Individual controller with specific logic is a good idea, because of better manageable code. I will use your idea if there is not any better one. Special thanks for fast answer :) – S.M.Mousavi Aug 13 '12 at 18:07
  • Yeah, no problem. Also - for some things such as edit or delete you may want to render the same thing, therefore making a single controller more useful – Troy Cosentino Aug 13 '12 at 19:18