【问题标题】:how to Delete post at the nested path如何在嵌套路径中删除帖子
【发布时间】:2015-11-02 13:08:11
【问题描述】:

我的代码有些问题。你能帮帮我吗?

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?' }

控制器/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

错误:

ActiveRecord::RecordNotFound in PostsController#destroy

找不到 'id'=# 的帖子

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

【问题讨论】:

    标签: ruby-on-rails controller nested destroy


    【解决方案1】:

    您的代码中有两个错误。

    1) 尝试在您的link_to 中将@post 对象更改为post,如下所示。

    也不确定您的@topics 对象,它应该保存一条记录。

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

    2) 在您的控制器中尝试更改破坏操作,如下所示:

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

    考虑到您在用户和帖子中有 has_many 关系。

    【讨论】:

      【解决方案2】:

      我想你在找post_path如果我错了请纠正我

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

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

      如果我的理解正确,这应该可以解决你的问题

      【讨论】:

        【解决方案3】:

        试试这个方法:

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

        控制器

        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.)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-01-31
          • 1970-01-01
          • 2015-03-09
          • 1970-01-01
          • 2020-06-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多