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

时间:2012-04-11 04:49:33

标签: ruby-on-rails resources routes

社团:

location  has_many :comments
comment  belongs_to :location

由于某种原因,这个GET:

/locations/5/comments.json 

表现得像这样GET:

/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“comments”。* FROM“comments”

路线设置如下:

  resources :locations do
    resources :comments
  end

Rake路线确认路线:

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

以下是索引操作:

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

这是正确的行动吗?这与结果一致,但我不确定还有什么应该在这里。我之前从未遇到嵌套资源的问题,所以我从未研究过细节。

1 个答案:

答案 0 :(得分:0)

试试这个:

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