我目前正在通过Michael Hartl的教程Ruby on Rails教程http://ruby.railstutorial.org/ruby-on-rails-tutorial-book。我对某些部分变量来自哪里感到困惑。在他的教程中,他创建了Users和Microposts。用户可以在他的主页上创建一个Micropost(称为Feed)并将它们发布到那里。布局看起来像这样http://ruby.railstutorial.org/chapters/user-microposts#fig:proto_feed_mockup。现在,用户模型看起来像这样(我不张贴整个事情):实例vs局部变量
class User < ActiveRecord::Base
has_many :microposts, dependent: :destroy
def feed
Micropost.where("user_id = ?", id)
end
end
的模型微柱看起来是这样的:
class Micropost < ActiveRecord::Base
belongs_to :user
end
在文本的作者说,进料方法内用户型号可以这样等效写入:
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变量来自哪里?它是否与调用此部分的@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来自何方,它包含哪些内容?
感谢, 麦克