Rails中的自定义路由,用于按字段搜索

时间:2012-11-02 20:39:23

标签: ruby-on-rails routes

我想添加一个到Rails应用程序的路由,所以我可以搜索除id之外的其他字段(并且仍然可以按id搜索)

def bycode
  @plot = Plot.find_by_code(params[:code])
  respond_to do |format|
    if !plot.nil?
      format.json {render json: @plot}
    else
      format.json
    end
  end
end

并在routes.rb中:

resources :plots do
  get 'bycode/:code' => 'plots#bycode'
end

在$ rake路线中我得到:

GET    /plots/:plot_id/bycode/:code(.:format) plots#bycode

我只是希望能够做到

http://myapp.com/plots/bycode?code=codename

或类似的东西

我错过了什么?

1 个答案:

答案 0 :(得分:1)

如果您使用RESTful路线(http://myapp.com/plots/<code>

,该怎么办?

并在您的控制器中

@plot = Plot.where(code: params[:id]).first || Plot.find(params[:id])
相关问题