Rails定义过滤器参数的方法

时间:2013-10-01 16:54:15

标签: ruby-on-rails

有以下路线:

  namespace :api do
    namespace :v1 do 
      resources :places, only: [:index]
    end
  end

控制器的代码:

class API::V1::PlacesController < API::V1::ApplicationController

  def index
    @places = (!params[:id]) ? Place.all : Place.find_all_by_type_id(params[:id])
    respond_to do |format|
      format.json { render json: @places }
      format.html
    end
  end   

end

&#39;将&#39;有&#39; type_id&#39;字段,我想通过其filter_id过滤地点。如您所见,现在我通过URL发送参数为&#34; places?id = 1&#34;。但可能是我必须发送参数为&#34; places / 1&#34;?我还需要建立路径;现在他们没有与&#34;?id = 1&#34;形成。请告诉我,我该怎么办?谢谢。

2 个答案:

答案 0 :(得分:1)

Rails惯例是将“index”操作中的位置列表映射到相对路径/places(GET方法)。

然后/places/1(GET)将映射到“show”,用于呈现集合的成员。对于“show”,路径会将路径(“1”)的ID段分配给params[:id]

The guides have a table of default route mappings.模型中的:type_id属性与路线中的:id属性可能会让您感到困惑。

一个简单的解决方案是使用/places?type_id=1代替。在您的控制器中,您可以使用以下内容:

def index
  collection = Place.all
  collection = collection.where(:type_id => params[:type_id].to_s) unless params[:type_id].to_s.blank?
  respond_to do |format|
    # ...
  end
end

:type_id设置为查询参数而不是集成到相对路径对我来说似乎特别合理,因为您正在构建API并且可能在将来添加对更多过滤器的支持。

答案 1 :(得分:0)

我的建议是像这样重写:

# Your routes
namespace :api do
  namespace :v1 do 
    resources :places, only: [:index]
    get "/places/by_type/:type_id" => "places#by_type", as: :places_by_type
  end
end

# Your controller

class API::V1::PlacesController < API::V1::ApplicationController
  def index
    respond_to do |format|
      format.json { render json: @places }
      format.html
    end
  end

  def by_type
    @places = Place.where(type_id: params[:type_id])
    respond_to do |format|
      format.js { render json: @places }
      format.html do
        render action: "index"
      end
    end
  end
end

我对这些路线可能有点不对劲,但我很确定它应该可行。