0
votes

The idea behind the project: Content Management System. I have a superclass called Content, and a subclass of Text/HTML, for now. Later it will handle content types of Video and Images. All using Single Table Inheritance.

My question is how to handle the subclass using only the parent class controller. Here is the code for create under ContentController (It might contain stuff I don't necessarily need):

def create
 @content = Content.new(params[:content])
 @content_module = ContentModule.find(@content.content_module_id)

 respond_to do |format|
  if @content.save
    format.html { redirect_to admin_module_content_url(@content.content_module), notice: 'Content was successfully created.' }
    format.json { render json: @content, status: :created, location: @content }
  else
    format.html { render action: "new"}
    format.json { render json: @content_module.errors, status: :unprocessable_entity}
  end
 end
end

The params to @content should be able to take in params of, let's say something like params[:text/html] which will create that type of Content.

Could someone help me out with the logic needed to do something like this?

1
How about simply setting the type of the Content (e.g. Content.type = 'SubClassName')?kwarrick

1 Answers

0
votes

I usually introduce a new class method on the superclass which returns the correct instance based on params[:type]:

class Content

  def self.for(params)
    content_type = params.delete(:type)
    case content_type
      when 'text_html'
        TextHtml
      when 'video'
        Video
      else
        raise "invalid content type #{content_type}"
    end.new(params)
  end

end

and then call it like this

@content = Content.for(params)

Does this help?