繁体   English   中英

迈克尔·哈特尔(Michael Hartl)的《 Rails教程》第10章销毁方法

[英]Michael Hartl's Rails Tutorial Chapter 10 destroy method

我有一个概念上的问题。 我目前正在研究著名的Micahel Hartl的Rails教程( http://ruby.railstutorial.org/ ),目前我正在阅读第10章。 作为一点背景,正在创建微博,并正在实施类似状态供稿的Twitter。 创建微型帖子后,它会显示在家庭状态供稿和个人资料页面中。 我的问题来自微博和feed_item对象之间的关系。 在本教程中,可以通过用户的个人资料或主页的供稿删除微博。 事实是,微博会根据用户的个人资料还是首页的供稿通过不同的部分删除。 这是局部的:

对于个人资料页面:

  <% if current_user?(micropost.user) %>
    <%= link_to "delete", micropost, method: :delete,
                                     data: { confirm: "You sure?" },
                                     title: micropost.content %>

对于主页状态供稿:

<li id="<%= feed_item.id %>">

  <span class="user">
    <%= link_to feed_item.user.name, feed_item.user %>
  </span>
  <span class="content"><%= feed_item.content %></span>
  <span class="timestamp">
    Posted <%= time_ago_in_words(feed_item.created_at) %> ago.
  </span>
    <% if current_user?(feed_item.user) %>
    <%= link_to "delete", feed_item, method: :delete,
                                     data: { confirm: "You sure?" },
                                     title: feed_item.content %>
  <% end %>
</li> 

以下是控制器,视图和模型:

class StaticPagesController < ApplicationController
  def home
    if signed_in?
      @micropost  = current_user.microposts.build
      @feed_items = current_user.feed.paginate(page: params[:page])
    end
  end

end

class User < ActiveRecord::Base
...
has_many :microposts,  dependent: :destroy
....
  def feed
    Micropost.where("user_id = ?", id)
  end
...
end

    class MicropostsController < ApplicationController
    before_action :signed_in_user, only: [:create, :destroy]
    before_action :correct_user,   only: :destroy
..

     def destroy
            @micropost.destroy
            redirect_to root_url
          end

...
    end

我假设正在通过Microposts Controller的destroy方法发生从主页状态提要中删除的微博,但是我不确定如何。 我在首页状态供稿中看到link_to的delete按钮具有delete方法,但它转到feed_item URL。 这个feed_item网址来自哪里? 我假设link_to知道某种方式删除微博,因为该提要的原始源来自User模型中的一系列微博,但是它怎么知道通过点击feed_item url转到微博的controller destroy方法? link_to“ title:feed_item.content”是否与知道删除哪个微博的feed_item有关系? 如果有人可以帮助我理解微博,feed_item和destroy方法之间的关系,我将不胜感激。 谢谢!

我可以为您提供DELETE方法的帮助,实际上这很简单:大多数浏览器都不支持PATCH,PUT和DELETE方法,因此Rails通过传递参数“ _method”并在内部进行转换来作弊。 这就是为什么您将它视为GET的原因,直到它到达Rails内部。

您可以在此处了解更多信息: http : //guides.rubyonrails.org/form_helpers.html#how-do-forms-with-patch-put-or-delete-methods-work-questionmark

高温超导

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM