2013-12-21 81 views
0

有一个在评论控制器下面的代码:如何检查Rails中是否存在关联对象?

def create 
    current_user.comments.create!(place: current_place, content: params[:content]) 
    render json: encode_result 
    end 

    private 
    def current_place 
     Place.find(params[:place_id]) 
    end 

此代码创建了当前用户和当前设立一个新的注解;如果当前的地方不存在,则此代码会抛出异常RecordNotFound。我可以发送'place_id'而不是'place'作为'create'方法,但是我需要在创建新评论之前检查是否存在位置。请告诉我,我的解决方案是否好,还有更好的方法吗?提前致谢。

回答

1

这是做它应该做的事情。你的代码是完美的,因为它现在写了。如果指定的记录不存在,您特别要停止执行。你所需要做的就是处理异常。

您可以通过rescue_from或整个应用程序将rescue_from放入您的ApplicationController来为您的整个控制器执行此操作。

0

你可以这样做.........

def create 
current_user.comments.create!(place: current_place, content: params[:content]) if current_place 
    render json: encode_result 
    end 

    private 
    def current_place 
     Place.find(params[:place_id]) 
    end 
+0

指定地点时,这将调用相同的查询两次,一个是如果条件和第二个:current_place。所以这不是一个最佳解决方案。尽量让它最优我正在投票 –

+0

好................. –