【发布时间】:2010-09-16 13:19:47
【问题描述】:
我有以下代码。我仍然是 Ruby on Rails 的新手。正如你所看到的,我重复了自己 4 次。
我尝试过这样的事情:
if @property.nil? || @property.status_id == 144 || (@property.status_id <= 16 && current_user.nil?) || (@property.status_id <= 16 && current_user.id != @property.user_id)
但如果@property 为nil,它会给我很多错误。因为那时@property.status_id 不能被调用,因为@property 为nil。
无论如何,我认为有经验的 Ruby on Rails 编码员会明白这一点。
def show
@property = Property.find(params[:id]) rescue nil
if @property.nil?
flash[:error]=t("The_property_was_not_found")
redirect_to root_path
return
end
if @property.status_id == 144
flash[:error]=t("The_property_was_not_found")
redirect_to root_path
return
end
if @property.status_id <= 16 && current_user.nil?
flash[:error]=t("The_property_was_not_found")
redirect_to root_path
return
end
if @property.status_id <= 16 && current_user.id != @property.user_id
flash[:error]=t("The_property_was_not_found")
redirect_to root_path
return
end
@images = Image.find(:all, :conditions =>{:property_id => params[:id]})
end
根
【问题讨论】:
-
通常您不需要让显示页面处理 nil 值。如果一开始就不存在,那么有人怎么能进入显示页面?
-
您应该将您的测试与
&&和||结合起来,这就是它们的用途。 -
@beerlington 这是一个房地产经纪人网站。从表中删除旧属性,使具有旧链接的访问者收到错误。你说得有道理,也许他们不应该删除旧属性。无论如何,这是一种保障。
-
这是有道理的。那么
current_user.nil?的逻辑是什么?用户是否也连同属性一起被删除?
标签: ruby-on-rails if-statement logic