【问题标题】:Ruby on Rails link_to explanation for a n00b?Ruby on Rails link_to 对 n00b 的解释?
【发布时间】:2014-02-24 13:58:16
【问题描述】:
  1. 我正在做一个 Rails 博客教程,不完全理解下面的 link_to 代码

    <%= link_to 'Destroy Comment', [comment.post, comment],
           method: :delete,
           data: { confirm: 'Are you sure?' } %>
    

    为什么一定要使用:

    [comment.post, comment] 
    

    为什么我不能直接写:

    @post.comment
    
  2. 我的第二个相关问题是,因为我在控制器中创建了“销毁”操作,如下所示:

    def destroy
      @post = Post.find(params[:post_id])
      @comment = @post.comments.find(params[:id])
      @comment.destroy
      redirect_to post_path(@post)
    

    结束

    为什么我不必在 link_to 代码中提到“销毁”?

    <%= link_to 'Destroy Comment', [comment.post, comment],
       method: :delete,
       data: { confirm: 'Are you sure?' } %>
    

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    您必须将 Post 对象和 Comment 都提供给 link_to 助手的原因是因为 Comment 是 Post 中的嵌套资源,并且必须知道这两个 ID 才能构造 URL。它实际上相当于:

    link_to 'Destroy Comment', post_comment_path(comment.post, comment), ...

    它正在做的是使用url_for 为您解析路径助手。见http://guides.rubyonrails.org/routing.html#creating-paths-and-urls-from-objects

    您不必在link_to 中提及destroy,因为destroy 是动作的名称。您的路由文件概述了哪些控制器和操作与哪些路由相关联。

    我假设您使用的是资源丰富的路由,这是为所有 CRUD 操作定义路由的简写方式。有关 HTTP 动词和控制器操作之间的映射,请参阅 http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions。您会看到delete 映射到destroy,并且您在link_to 上使用method: :delete

    【讨论】:

      【解决方案2】:

      所以这里发生了很多事情。

      1) 我的猜测是第一部分中的link_to 在一个循环中。真的吗?那将类似于@post.comments.each do |comment|。如果是这种情况,那么很可能发生的事情是您将 cmets 嵌套在帖子下。可以在here 找到该文档。方括号用于标识您需要 post id 的评论。您也可以使用[@post, comment],它也可以。你不能只写@post.comment,因为它没有足够的信息来识别正确的评论。

      2) Rails 使用 HTTP 动词来识别从控制器调用哪个动作。您正在向/posts/:post_id/comments/:id 发送一个HTTP DELETE 请求,然后路由文件确定该请求属于cmets 控制器。可以在 herehere 找到该文档。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-27
        • 1970-01-01
        • 2013-03-06
        • 1970-01-01
        相关资源
        最近更新 更多