我在用Rails 4并出现以下错误。
路由错误
没有路线匹配 [POST] "/logs/1/meals/13/edit
我使用 :meal 传递模型对象的 form_ ,并且编辑页面正确呈现。然而,Rails 似乎并没有检查膳食对象是否已经保存,因此它不断尝试将表单发送到 #create 操作,并尝试发出 POST 请求,而不是将表单发送到更新操作并进行当我点击提交时发出 PUT 请求。
如何让 form_for 识别出我正在尝试更新现有对象并且需要 PUT 而不是 POST?其他一切都正常,我已经运行了所有迁移。我对 Rails 还很陌生,我几乎花了一整天的时间试图自己解决这个问题。请帮忙!
需要注意的是,当我尝试将模型对象作为 @meal.log 而不是 :meal 传递时,Rails 不再能够识别 :calorie_estimate 或 :meal_description。将模型对象作为 @meal.log 传递给我留下了无方法错误。
膳食/edit.html.erb
<h3> EDIT MEAL </h3>
<%= form_for(:meal) do |f| %>
<div id="meal-form">
<%= f.text_field :calorie_estimate, class: 'meal-form-fields', :placeholder => "Calorie Estimate" %>
<%= f.text_field :meal_description, class: 'meal-form-fields', :placeholder => "Food Description" %>
<div class="submit-form" style="width: 75px; height: 15px;">
<%= f.submit 'UPDATE', :class => 'submit-form-text' %>
</div>
</div>
<% end %>
餐食控制器.rb
class MealsController < ApplicationController
include MealsHelper
def create
@meal = Meal.new(meal_params)
@meal.log_id = params[:log_id]
@meal.save
redirect_to log_path(@meal.log)
end
def edit
@meal = Meal.find(params[:id])
end
def update
@meal = Meal.find(params[:id])
@meal.update(meal_params)
redirect_to log_path(@log)
end
def meal_params
params.require(:meal).permit(:calorie_estimate, :meal_description)
end
end
可能的路线:
Prefix Verb URI Pattern Controller#Action
root GET / logs#index
log_meals GET /logs/:log_id/meals(.:format) meals#index
POST /logs/:log_id/meals(.:format) meals#create
new_log_meal GET /logs/:log_id/meals/new(.:format) meals#new
edit_log_meal GET /logs/:log_id/meals/:id/edit(.:format) meals#edit
log_meal GET /logs/:log_id/meals/:id(.:format) meals#show
PATCH /logs/:log_id/meals/:id(.:format) meals#update
PUT /logs/:log_id/meals/:id(.:format) meals#update
DELETE /logs/:log_id/meals/:id(.:format) meals#destroy
logs GET /logs(.:format) logs#index
POST /logs(.:format) logs#create
new_log GET /logs/new(.:format) logs#new
edit_log GET /logs/:id/edit(.:format) logs#edit
log GET /logs/:id(.:format) logs#show
PATCH /logs/:id(.:format) logs#update
PUT /logs/:id(.:format) logs#update
DELETE /logs/:id(.:format) logs#destroy
路线.rb
Rails.application.routes.draw do
root to: 'logs#index'
resources :logs do
resources :meals
end
end
模式.rb
ActiveRecord::Schema.define(version: 20160128205351) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "logs", force: :cascade do |t|
t.string "entry_date"
t.integer "calorie_goal"
t.string "notes"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "meals", force: :cascade do |t|
t.integer "calorie_estimate"
t.string "meal_description"
t.integer "log_id"
t.datetime "created_at"
t.datetime "updated_at"
end
end