Ask A Question

Notifications

You’re not receiving notifications from this thread.

let users edit their own posts

Erick Sitter asked in General

I currently have it setup to where only the admin can edit posts, but would like if the user can edit their posts but no other posts that were not made by them.

Forum Posts Controller

class ForumThreads::ForumPostsController < ApplicationController
before_action :authenticate_user!
before_action :set_forum_thread

def create
@forum_post = @forum_thread.forum_posts.new forum_post_params
@forum_post.user = current_user

if @forum_post.save
  redirect_to forum_thread_path(@forum_thread, anchor: "forum_post_#{@forum_post.id}"), notice: "Successfully posted!"
else
  redirect_to @forum_thread, alert: "Unable to save your post"
end

end

def edit
@forum_thread = ForumThread.friendly.find(params[:forum_thread_id])
@forum_post = ForumPost.find(params[:id])
@forum_post = current_user.forum_posts.find(params[:id])
end

def update
@forum_post = ForumPost.find(params[:id])
if @forum_post.update(forum_post_params)
redirect_to @forum_thread
else
render 'edit'
end
end

def destroy
@forum_post = ForumPost.find(params[:id])
@forum_post.destroy
redirect_to @forum_thread
end

private

def set_forum_thread
  @forum_thread = ForumThread.friendly.find(params[:forum_thread_id])
end

def forum_post_params
  params.require(:forum_post).permit(:body)
end

end

HTML

<%= div_for @forum_post do %>

<%= image_tag forum_post.user.gravatar_url(:size => 55), :class => "img-circle avatar" %>

Posted by <%= forum_post.user.username %> <%= local_time_ago forum_post.created_at %> <% if current_user.admin %> <%= link_to edit_forum_thread_forum_post_path(@forum_thread, forum_post), class: "btn btn-info btn-xs" do %> <% end %> <% end %> <% if current_user.admin %> <%= link_to forum_thread_forum_post_path(@forum_thread, forum_post), method: :delete, data: { confirm: "Are you sure you want to do this?" }, class: "btn btn-danger btn-xs" do %> <% end %> <% end %>

<%= markdownify forum_post.body %>

<% end %>

Reply

You should take a look at his episode on the pundit gem. Sounds like exactly what you need. :)

Reply

You beat me to it! Pundit's exactly the right thing for this.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 87,563+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.