开发者

Saving a simple blog post, should create and update methods be the same?

To 开发者_运维技巧avoid duplicating logic, should the create and update actions be the same?

ANy good examples of this?


The create method is responsible for creating that simple blog post, whilst the update method is responsible for updating it.

def create
  @blog = Blog.new(params[:blog])
  if @blog.save
    flash[:notice] = "Saved!"
    redirect_to @blog
  end
end

def update
  @blog = Blog.find(params[:id])
  if @blog.update_attributes(params[:blog])
    flash[:notice] = "Saved!"
    redirect_to @blog
  end
end

Not much you could extract out of that besides what to do when the save succeeds / fails.


While create and update are similar, I don't think it worthwhile to make them literally the same. Usually you'll want different flash messages for each. Also, should a validation fail, on create it's usually best to render your new action, while on a failed update, you're more likely to want to render the edit action. These little differences are typically enough so that it's simpler and more readable to have separate create and new methods.

I personally would have an else clause for each of create and update. They would look like:

#create
else
  render :action => "new"
end

#update
else
  render :action => "edit"
end

The user can still see the error and correct it, but this way I don't need create and update views at all.

If you were to use save! or update_attributes! any validation error would raise an exception, which you'd have to rescue somewhere. If you didn't rescue it, your users would receive a 500 error page every time a model failed to validate. That's why its more conventional to use the non-! save and update_attributes methods.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜