实例vs部分中的局部变量

时间:2012-07-11 23:15:55

标签: ruby ruby-on-rails-3

我目前正在阅读Michael Hartl的教程Ruby on Rails教程http://ruby.railstutorial.org/ruby-on-rails-tutorial-book。我对某些部分变量的来源感到困惑。在他的教程中,他创建了用户和微博。用户可以在他的主页面上创建一个Micropost(称为Feed)并将其发布在那里。布局看起来像http://ruby.railstutorial.org/chapters/user-microposts#fig:proto_feed_mockup。现在User模型看起来像这样(我没有发布整个事情):

class User < ActiveRecord::Base
  has_many :microposts, dependent: :destroy

  def feed
    Micropost.where("user_id = ?", id)
  end
end

Micropost模型如下所示:

class Micropost < ActiveRecord::Base
  belongs_to :user
end

在文中,作者说用户模型中的feed方法可以像这样写成:

def feed
  microposts
end

为什么它们一样?

我的下一个问题与偏见有关。在用户的节目页面(show.html.erb)上,如果我没弄错的话,_microposts.html.erb会被调用:

<%= render @microposts %>

_microposts.html.erb看起来像这样:

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

我的问题是微博变量来自哪里?它与调用此部分的@micropost变量相同吗?

现在在用户主页(home.html.erb)上有一个对_feed.html.erb部分的调用,如下所示:

<%= render 'shared/feed' %>

_feed.html.erb看起来像这样:

<% if @feed_items.any? %>
  <ol class="microposts">
    <%= render partial: 'shared/feed_item', collection: @feed_items %>
  </ol>
  <%= will_paginate @feed_items %>
<% end %>    

我知道@feed_items的来源。它设置在一个控制器中。现在_feed_item.html.erb看起来像这样:

<li id="<%= feed_item.id %>">
  <%= link_to gravatar_for(feed_item.user), feed_item.user %>
  <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>

所以类似的问题是变量feed_item来自何处以及它包含什么?

感谢, 麦克

2 个答案:

答案 0 :(得分:1)

好的,让我们看看。这是一次性的很多问题,但是......

  1. 为什么'feed'等同于'microposts'? 这是Rails的工作协会。当您使用has_many来描述关联时,Rails会根据关联名称创建一大堆方法。在这种情况下,您说的是用户has_many :microposts,其中包括创建User#microposts方法。

  2. 渲染调用中使用的实例变量(@microposts)可能是在控制器操作中设置的。当您以这种方式调用render(使用ActiveRecord对象数组)时,Rails会查找名称与这些对象的类名匹配的部分。在这种情况下,它们是MicroPost对象,因此它会查找名为_micropost的部分,并为数组中的每个对象呈现一次。渲染局部时,可以使用与局部同名的局部变量来引用与局部相关联的对象。由于这是_micropost部分,因此本地micropost变量引用它所呈现的对象。

  3. 同样,与partial同名的局部变量引用局部渲染的对象。 @feed_items是一个集合,对于其中的每个对象,您将获得_feed_item部分的一个呈现,其中feed_item局部变量引用该对象。

答案 1 :(得分:0)

  1. 因为用户的微博使用has_many关联,并且在内部,关系基于用户的ID。 “手动”获取它们基本上是相同的,但需要更多的工作。
  2. micropost来自约定--Rails为您创建。我不知道你所谓的“@micropost变量调用这个部分”。
  3. 同样的答案,虽然它明确基于模板名称(IIRC)而不是单一化的名称。它包含@feed_items包含的任何内容。
相关问题