我有一个关于过程的问题,如果我可以这样做一个更好的方法。我正在开发一个rails应用程序,并且当certian元素不存在时,我会遇到页面错误。例如这里是我的节目动作过度使用“.present?”在轨道控制器
def show
@article = Article.friendly.find(params[:article_slug])
@section_slug = Section.find_by_id(@article.section_id).slug if @article.section_id.present?
@issue_slug = Issue.find_by_id(@article.issue_id).slug if @article.issue_id.present?
@next_article = @article.next_article if @article.next_article.present?
@prev_article = @article.prev_article if @article.prev_article.present?
@article_author = Author.find_by_id(@article.author_id)
render :layout => 'magazine'
session[:return_to] = request.referer
#if request.path != article_path(@article)
#return redirect_to @article, :status => :moved_permanently
#end
end
我应该使用.present吗?就像我一样?如果某个元素不存在,是否有更好的方法可以使页面不会失败?只是试图以一种可以导致更好的代码的方式学习rails。
对于情况下,你真正需要'Y = X如果x.present?',检查出[存在](http://api.rubyonrails.org/classes/Object.html#method-i-存在)方便的方法。我会听Carl Zulauf关于尽量减少控制器实例变量的建议。如果你的模型设计得很好,很少有必要有一两个(RubyMine实际上会给你警告)。 – Jimeux