【问题标题】:Custom route in Rails for searching by fieldRails 中用于按字段搜索的自定义路线
【发布时间】:2012-11-02 20:39:22
【问题描述】:

我想向 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

或类似的东西

我错过了什么?

【问题讨论】:

    标签: ruby-on-rails routes


    【解决方案1】:

    如果你使用 RESTful 路由(http://myapp.com/plots/<code>)会怎样

    在你的控制器中

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

    【讨论】:

    • myapp.com/plots?code=codename 只是带​​我去 plots#index 并希望保留使用 common plots/:id path 的选项
    • 我明白了,任何给定代码都只有一个情节...这应该是#show 类型的路线...
    • 成功了!但是由于某种原因不得不做@plot =Plot.find_by_code(params[:id]) || Plot.find(params[:id]) 代替(否则失败)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    • 2021-08-19
    • 2020-06-07
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多