Reputation:
I'm a beginner in Ruby on Rails and stack overflow. So sorry if there are mistakes in asking this question or...
I'm trying to write 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 view:
<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 post I keep getting this error:
NoMethodError in PostsController#update
undefined method `update' for nil:NilClass
Any help will be appreciated! :)
Upvotes: 7
Views: 16791
Reputation: 8055
You can also set @post
using a 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, whenever rails hits your edit
or update
actions it will set @post
to the "current" post.
Upvotes: 2
Reputation: 51151
You must set @post
instance variable to point appropriate Post
object in order to perform update on it:
@post = Post.find params[:id]
Upvotes: 11