user4380892
user4380892

Reputation:

how to Delete post at the nested path

I have some trouble with my code. Could you help me?

views/topics/show.html.slim

- if current_user == post.user
  = link_to 'Удалить комментарий',forum_topic_post_path(@forum, @topics, @posts, @post),
        method: :delete,
        data: { confirm: 'Are you sure?' }

controllers/post_controller.rb

def destroy
    @forum = Forum.find params[:forum_id]
    @topic = Topic.find params[:topic_id]
    @post.user = current_user
    @post = Post.find(params[:id]).destroy
end

error:

ActiveRecord::RecordNotFound in PostsController#destroy

Couldn't find Post with 'id'=#

@post = Post.find(params[:id]).destroy

Upvotes: 0

Views: 238

Answers (3)

7urkm3n
7urkm3n

Reputation: 6311

Try this way:

- if current_user == post.user
 = link_to 'Удалить комментарий',forum_topic_post_path(@forum, @topics, @post),
   method: :delete, data: { confirm: 'Are you sure?' }

Controller

before_action :check_user, only: [:destroy]

def destroy
    @forum = Forum.find params[:forum_id]
    @topic = Topic.find params[:topic_id]
    @post.destroy 
end

private

def check_user
  if current_user != @product.user
    redirect_to root_url, alert: "Sorry, This Post belongs to someone else !"
  end
end

(mne kajetsa tebe ne nado ispolzovat "current_user" dla udalenie post.)

Upvotes: 0

user5412340
user5412340

Reputation:

I think you are looking for post_path correct me if I am wrong

= link_to 'Удалить комментарий', post_path(post,:forum_id =>@forum.id, :topic_id =>@topic.id),
    method: :delete,
    data: { confirm: 'Are you sure?' }

or

= link_to 'Удалить комментарий', forum_topic_post_path(@forum, @topics, post),
    method: :delete,
    data: { confirm: 'Are you sure?' }

If I have got you correctly this should solve your problem

Upvotes: 0

Nitin
Nitin

Reputation: 7366

You have two mistake in your code.

1) Try change @post object to post in your link_to like below.

Also not sure about your @topics object, It should hold a single record.

- if current_user == post.user
  = link_to 'Удалить комментарий',forum_topic_post_path(@forum, @topics, post),
    method: :delete,
    data: { confirm: 'Are you sure?' }

2) In your controller try changes destroy action as below:

def destroy
  @forum = Forum.find params[:forum_id]
  @topic = Topic.find params[:topic_id]
  @post = current_user.posts.find(params[:id]).destroy
end

Considering you have has_many relationship in user and posts.

Upvotes: 0

Related Questions