我已经阅读了 20 多篇关于非常相似的问题的 StackOverflow 文章(以及网络上的许多其他文章),并尝试了他们的解决方案,但都没有奏效。请帮助这个初学者!
特别是,我最常发现的解决方案是
form_for [@parent, @child] do |f|
但它并没有像其他人那样修复错误。
错误:
错误发生在 localhost:3000/locations/1/restaurants/new
餐厅中的 NoMethodError#new
显示第 1 行引发的 /app/views/restaurants/_form.html.erb :
undefined method `restaurants_path' for #<#<Class:0x007fb7ab89ea80>:0x007fb7aaadc3c0>
提取的源代码(在第 1 行附近):
1: <%= form_for [@location, @restaurant] do |f| %>
2: <% if @restaurant.errors.any? %>
3: <div id="error_explanation">
4: <h2><%= pluralize(@restaurant.errors.count, "error") %> prohibited this restaurant from being saved:</h2>
我在任何应用程序代码中都找不到任何关于restaurants_path的提及,所以我假设它是一些神奇的Rails 默认值。
代码:
我正在使用has_many/belongs_to模型:一个位置有很多餐馆。
配置/路由.rb
resources :locations do
resources :restaurants
end
$ rake 路线
location_restaurants GET /locations/:location_id/restaurants(.:format) restaurants#index
POST /locations/:location_id/restaurants(.:format) restaurants#create
new_location_restaurant GET /locations/:location_id/restaurants/new(.:format) restaurants#new
edit_location_restaurant GET /locations/:location_id/restaurants/:id/edit(.:format) restaurants#edit
location_restaurant GET /locations/:location_id/restaurants/:id(.:format) restaurants#show
PUT /locations/:location_id/restaurants/:id(.:format) restaurants#update
DELETE /locations/:location_id/restaurants/:id(.:format) restaurants#destroy
应用程序/控制器/restaurants_controller.rb
def new
@restaurant = Restaurant.new
respond_to do |format|
format.html
format.json { render json: @restaurant }
end
end
def edit
@restaurant = Restaurant.find(params[:id])
end
def create
@location = Location.find(params[:location_id])
@restaurant = @location.restaurants.create(params[:restaurant])
respond_to do |format|
if @restaurant.save
format.html { redirect_to location_restaurants_path(@location), notice: 'Restaurant was successfully created.' }
format.json { render json: @restaurant, status: :created, location: @restaurant }
else
format.html { render action: "new" }
format.json { render json: @restaurant.errors, status: :unprocessable_entity }
end
end
end