2012-10-04 65 views
0

我使用Ruby on Rails 3.2并创建了一个简单的测试博客应用程序。有一个Post模型和一个评论模型,其中一个帖子has_many :comments和一个评论belongs_to :postRails 3.2嵌套路由和AJAX

在routes.rb中:

resources "posts" do 
    resources "comments" 
end 

我显示在父后的页面底部的意见,并通过AJAX提交新的评论。因此,我认为用户无需访问/ posts/1/comments/XXX即可。但是,如果我从我的路线中删除resources "comments",则评论功能不再有效。如何防止用户在浏览器中访问/ posts/1/comments/XXX,但保持评论AJAX功能的正常工作?

回答

3

作为一种解决方案,您可以做些什么来处理请求是xhr请求的路由。你可以做到这一点通过以下方式:

# routes.rb 
class OnlyAjaxRequest 
    def matches?(request) 
    request.xhr? 
    end 
end 

resources "posts" do 
    resources "comments", :constraints => OnlyAjaxRequest.new 
end 

您可以找到有关this blog post布线约束的详细信息。