我在非常相似的问题上阅读了20多篇StackOverflow文章(还有很多其他文章),并尝试了他们的解决方案,但都没有奏效。请帮助这个初学者!
特别是,我经常找到的解决方案是
form_for [@parent, @child] do |f|
但它并没有像对待其他人一样修复错误。
错误发生在localhost:3000 / locations / 1 / restaurants / new
餐馆中的NoMethodError#new
显示/app/views/restaurants/_form.html.erb,其中第1行引发:
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 模特:一个地方有很多餐馆。
配置/ routes.rb中
resources :locations do
resources :restaurants
end
$ rake routes
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
答案 0 :(得分:1)
您尚未初始化表单所需的@location
(在form_for [@location, @restaurant]
行中)。只需在Location.find
操作中添加一行(使用new
)查找该行,然后构建@restaurant
以便与该位置相关联:
def new
@location = Location.find(params[:location_id])
@restaurant = @location.restaurants.build
...
end
由于您的所有操作都需要@location
(包括edit
,我认为这些操作不能在您当前的代码中运行),因此将它放入单独的方法中是有意义的然后从before_filter
调用它,即:
before_filter :find_location
private
def find_location
@location = Location.find(params[:location_id])
end
然后,您还可以删除在create
操作中找到位置的行(以及new
操作)。
答案 1 :(得分:0)
我认为问题在于您在@restaurant
操作中实例化new
变量的方式。因为它嵌套在位置下,所以需要按原样构建它:
@location = Location.find(params[:location_id])
@restaurant = @location.restaurants.new