Undefined `update 'method for nil: NilClass 4.0.0 rails

I am new to Ruby on Rails and stack overflow. Sorry if there are errors in asking this question or ...

I am trying to write an edit / update for my blogger project. This is my controller:

def edit @post = Post.find params[:id] end def update @post.update(params[:post].permit(:title, :summary, :content)) redirect_to posts_path end 

This is my opinion:

 <h1>Edit Page</h1> <%= form_for @post do |f| %> Title: <%= f.text_field :title %> Summary: <%= f.text_area :summary %> Content: <%= f.text_area :content %> <%= f.submit "Update" %> <% end %> 

and when I want to update any record, I keep getting this error:

NoMethodError in PostsController Update #

undefined `update 'method for nil: NilClass

Any help would be appreciated! :)

+6
source share
2 answers

You must set the @post instance variable to indicate the appropriate Post object in order to update:

 @post = Post.find params[:id] 
+10
source

You can also set @post with before_action

 class PostsController < ApplicationController before_action :set_post, only: [:edit, :update] # GET /posts/1/edit def edit end # PATCH/PUT /posts/1 # PATCH/PUT /posts/1.json def update end private # Use callbacks to share common setup or constraints between actions. def set_post @post = Post.find(params[:id]) end end 

Now that the rails fall into your edit or update actions, it sets @post to the β€œcurrent” entry.

+1
source

Source: https://habr.com/ru/post/950171/


All Articles