S.M.Mousavi
S.M.Mousavi

Reputation: 5246

How can i use multiple controller with one model?

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?

Upvotes: 4

Views: 4146

Answers (2)

Beno&#238;t
Beno&#238;t

Reputation: 15010

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?

Upvotes: 3

Troy Cosentino
Troy Cosentino

Reputation: 4778

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

Upvotes: 1

Related Questions