I am using Rails 4 and have the following error.
Routing error
No route matches [POST] "/ logs / 1 / meal / 13 / edit
Im passing form_ to the model object using: the food and the edit page are displayed correctly. However, Rails doesn't seem to check if the food object is saved or not, so it tries to submit the form to the #create action and tries to make a POST request instead of submitting the form to the update action and the PUT request when I hit submit.
How do I get form_for to recognize that I am trying to update an existing object and that PUT is needed instead of POST? Everything else works, and Ive triggered all my migrations. Im pretty new to Rails, and Ive spent almost all day trying to figure it out on my own. Please help!
And just to mention, when I tried to pass the model object as @ meal.log instead of: meal, Rails could no longer recognize: calorie_estimate or: meal_description. Passing the model object as @ meal.log left me without a method error.
nutrition / 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 %>
meals_controller.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
possible routes:
Prefix Verb URI Pattern Controller
routes.rb
Rails.application.routes.draw do root to: 'logs#index' resources :logs do resources :meals end end
schema.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