Ruby on rails Rails ActiveRecord关系-避免写入。空白?检查

Ruby on rails Rails ActiveRecord关系-避免写入。空白?检查,ruby-on-rails,rails-activerecord,Ruby On Rails,Rails Activerecord,这更像是一个风格问题,而不是什么 在编写查询时,我总是检查查询结果是否为空,我不知道,这似乎过于冗长或在某种程度上是错误的 前 如果没有name=params[:name]的产品,我会得到一个nil值,该值会破坏一切 我开始写这样的东西 def some_action product = Product.where(:name -> params[:name]) @product = product if !product.blank? end 有没有更简洁的方法来处理nil和空

这更像是一个风格问题,而不是什么

在编写查询时,我总是检查查询结果是否为空,我不知道,这似乎过于冗长或在某种程度上是错误的

如果没有name=params[:name]的产品,我会得到一个nil值,该值会破坏一切

我开始写这样的东西

def some_action
  product = Product.where(:name -> params[:name])
  @product = product if !product.blank?
end
有没有更简洁的方法来处理nil和空白值?当事情依赖于其他关系时,这变得更令人头痛

基本上,有什么我没有;我还没学会如何更有效地处理nil、blank和可能破坏视图的实例变量


谢谢

即使您在控制器中使用“零破坏东西”,您的视图中仍然会出现该问题。在控制器中有一个
if
语句并将视图重定向到“notfound”页面要比在视图中有几个
if
语句容易得多

或者你可以加上这个

protected
  def rescue_not_found
  render :template => 'application/not_found', :status => :not_found
end

到您的
应用程序\u控制器
。在这里看到更多:

< P>如果它只是风格相关,我会看Rails的对象方法,或者考虑类似的东西。 使用您的示例,尝试:

def some_action
  @order = Order.where(:id => params[:id]).first
  @products_on_sale = @order.try(:where, {:onsale => true}).try(:all)
end
或使用AND和:

def some_action
  @order = Order.where(:id => params[:id]).first
  @products_on_sale = @order.andand.where(:onsale => true).andand.all
end

酷,这正是我想要的信息。谢谢非常有趣,有两种方法我以前没见过。太棒了,谢谢!
def some_action
  @order = Order.where(:id => params[:id]).first
  @products_on_sale = @order.try(:where, {:onsale => true}).try(:all)
end
def some_action
  @order = Order.where(:id => params[:id]).first
  @products_on_sale = @order.andand.where(:onsale => true).andand.all
end