2012-04-11 147 views
2

协会:为什么Rails 3嵌套路由忽略嵌套资源?

location has_many :comments 
comment belongs_to :location 

出于某种原因,这个GET:

/locations/5/comments.json 

行事像这样得到:

/comments.json 

Started GET "/locations/5/comments.json" for 127.0.0.1 at 2012-04-10 21:18:00 -0700 
    Processing by CommentsController#index as JSON 
    Parameters: {"location_id"=>"5"} 
    Comment Load (0.1ms) SELECT "comments".* FROM "comments" 
Completed 200 OK in 21ms (Views: 1.0ms | ActiveRecord: 0.7ms) 

注意SQL查询:SELECT “意见” * FROM “意见”

路线设置是这样的:

resources :locations do 
    resources :comments 
    end 

耙路线确认路线:

location_comments GET /locations/:location_id/comments(.:format)   {:action=>"index", :controller=>"comments"} 

这里是index动作:

def index 
    @comments = Comment.all 
    respond_to do |format| 
     format.json { render json: @comments } 
    end 
    end 

这是正确的行动?这与结果是一致的,但我不知道还有什么应该在这里。我以前从来没有遇到嵌套资源的问题,所以我从来没有看过细节。

+0

没有找到任何意外。这有什么问题? – prasvin 2012-04-11 04:57:42

+0

生成的查询应该是SELECT“comments”。* FROM“comments”WHERE“comments”。“location_id”= 5. – 2012-04-11 12:00:41

+1

不,嵌套不会使查询自动执行。如果是这样,你会如何得到所有的评论,而不考虑位置。可能是'@comments = Comment.all.without_nesting',它比传统方式更不清洁。 就你而言,你可以很容易地获得@Patrick建议的特定位置的评论。 – prasvin 2012-04-11 12:28:17

回答

0

试试这个:我好像

def index 
    @location = Location.find(params[:location_id]) 
    @comments = @location.comments 
    respond_to do |format| 
    format.json { render json: @comments } 
    end 
end 
+0

你也可以用'respond_with @ comments'替换整个'respond_to'块。 – 2012-04-11 05:08:23

+0

感谢Patrick,这会起作用,但是以敲除常规索引操作为代价。你可以证实我错了,我假设嵌套应该自动工作以产生一个像WHERE“comments”这样的条件的SQL查询。“location_id”= 5?而且我必须重写一个行动才能完成这项工作? – 2012-04-11 12:08:44

+0

一个稍微丑陋的条件恢复常规索引操作:if params [:location_id] – 2012-04-11 13:04:57