项目背后的理念:内容管理系统。我现在有一个名为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,比如params [:text / html]这样可以创建那种类型的内容。
有人可以帮我解决做这样的事情需要的逻辑吗?
答案 0 :(得分: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)
这有帮助吗?