Reputation: 2353
I know that's old question, but I don't understand why code, that worked half a year ago doesn't work. So I want to make only owners can have access to their posts. I thaught it could be written like this:
def create
@post = current_user.posts.new params[:post]
if @post.save
flash[:notice] = 'Post created'
redirect_to @post
else
render :new
end
end
and in edit and others controllers
def edit
if (current_user.id == @post.user_id)
@post = Post.find params[:id]
else
flash[:notice] = 'You are not owner!'
end
end|
but in views I get, when I'm logged in:
undefined method `user_id' for nil:NilClass
Where is my problem ?
Upvotes: 0
Views: 41
Reputation: 160833
def edit
# The @post is nil unless you set it in a before filter.
if (current_user.id == @post.user_id)
@post = Post.find params[:id]
else
flash[:notice] = 'You are not owner!'
end
end
You should find the post first.
def edit
@post = Post.find params[:id]
if (current_user.id != @post.user_id)
flash[:notice] = 'You are not owner!'
end
end
Upvotes: 2