【问题标题】:Create info page for each restaurant with Ruby on Rails使用 Ruby on Rails 为每家餐厅创建信息页面
【发布时间】:2017-07-30 15:34:02
【问题描述】:

我正在尝试在 Ruby on rails 应用程序中为每家餐厅创建一个信息页面。我在Restaurant controller 中创建了一个动作info,并在routes.rb 中添加了一行。但它给出了一个错误

“ActiveRecord::RecordNotFound in RestaurantsController#info”不能 查找具有 'id'=.. 的餐厅。

我的代码有什么问题?

这是我的餐厅控制器:

class RestaurantsController < ApplicationController
 before_action :set_restaurant, only: [:show, :edit, :update, :destroy, :info]

  def info
  end 

  private
  def set_restaurant
    @restaurant = Restaurant.find(params[:id]) 
  end
end

这是我的路线.rb:

Rails.application.routes.draw do

 resources :restaurants do 
  get '/info', to: 'restaurants#info'
 end

end

这是餐厅信息页面的链接:

<%= link_to 'Info', restaurant_info_path(@restaurant) %> 

【问题讨论】:

  • 这行&lt;%= link_to 'Info', restaurant_info_path(@restaurant) %&gt;在哪个页面?
  • 感谢您的回复!在餐厅展示页面中。

标签: ruby-on-rails ruby info


【解决方案1】:

ActiveRecord::RecordNotFound in RestaurantsController#info

通过将自定义路由嵌套在resources :restaurants中,生成带有错误键的路由。当你运行rake routes时,你可以看到这条路线

restaurant_info GET  /restaurants/:restaurant_id/info(.:format)  restaurants#info

所以这条路线有:restaurant_id 而不是:id。所以你不能用params[:id] 来获取@restaurant = Restaurant.find(params[:id]) 这一行中的值,这会因错误而失败。将 params[:id] 更改为 params[:restaurant_id] 应该可以解决您的问题,但这不是正确的解决方案。

显而易见且理想的解决方案是调整您的自定义路线,使其可以像这样生成

 restaurant_info GET  /restaurants/:id/info(.:format)  restaurants#info

您可以将自定义路由调整到下方以实现此目的,而不是将其嵌套在 resources :restaurants

get 'restaurants/:id/info', to: 'restaurants#info', as: :restaurant_info
resources :restaurants

【讨论】:

  • 非常感谢您的帮助和详细的解释
  • “restaurants/:id/info”不是更好的 REST 路由吗?
  • @m.simonborg 感谢您的通知!我实际上忘了编辑它:)
【解决方案2】:

这是因为set_restaurant 方法没有获取任何参数,请检查并返回是否正确接收它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多