0

项目背后的理念:内容管理系统。我现在有一个名为 Content 的超类和一个 Text/HTML 的子类。稍后它将处理视频和图像的内容类型。全部使用单表继承。

我的问题是如何只使用父类控制器来处理子类。这是在 ContentController 下创建的代码(它可能包含我不一定需要的东西):

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

@content 的参数应该能够接受参数,比如 params[:text/html] 之类的参数,它将创建那种类型的内容。

有人可以帮助我解决执行此类操作所需的逻辑吗?

4

1 回答 1

0

我通常在超类上引入一个新的类方法,它根据 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

然后这样称呼它

@content = Content.for(params)

这有帮助吗?

于 2013-11-07T22:52:56.100 回答