上节初步实现了用户发微博的功能,现在增加一个动态列表 。
4.动态列表
这个列表显示在首页,主要是为了显示用户关注的其他用户的动态,这里暂且显示用户自己的动态。
在User的Model中加入:
def feed
# This is preliminary. See "Following users" for the full implementation.
Micropost.where("user_id = ?", id)
end
feed暂时还没有什么实际作用,他的实际用处是返回所有关注用户的微博。
在home中加入一个实例变量
def home
if signed_in?
@micropost = current_user.microposts.build
@feed_items = current_user.feed.paginate(page: params[:page])
end
end
动态列表的局部视图:
<% if @feed_items.any? %>
<ol class="microposts">
<%= render partial: 'shared/feed_item', collection: @feed_items %>
</ol>
<%= will_paginate @feed_items %>
<% end %>
单个动态列表项目的局部视图:
<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>
</li>
首页中加入动态列表:
<div class="span8">
<h3>Micropost Feed</h3>
<%= render 'shared/feed' %>
</div>
不过还有个小小不足:如果发布微博失败,首页还会需要一个名为 @feed_items 的实例变量,所以提交失败时网站就无法正常运行了。最简单的解决方法是,如果提交失败就把 @feed_items 设为空数组:
def create
@micropost = current_user.microposts.build(micropost_params)
if @micropost.save
flash[:success] = "Micropost created!"
redirect_to root_url
else
@feed_items = []
render 'static_pages/home'
end
end
至此就初步实现了动态列表。
5. 删除微博
在微博局部视图_micropost.html.erb中加入删除链接:
<% if current_user?(micropost.user) %>
<%= link_to "delete", micropost, method: :delete,
data: { confirm: "You sure?" },
title: micropost.content %>
<% end %>
在_feed_item.html.erb中同样也加入:
<% if current_user?(feed_item.user) %>
<%= link_to "delete", feed_item, method: :delete,
data: { confirm: "You sure?" },
title: feed_item.content %>
<% end %>
在Micropost控制器中加入:
def destroy
@micropost.destroy
redirect_to root_url
end
上节提到无论是create还是destroy都必须登录,这里必须在加上一个限制,就是用户删除的必须是自己的微博,前面实际上已经加了限制,就是只有当前用户才能看到删除链接,但防止有人伪造delete请求,于是
加入一个私有方法:
def correct_user
@micropost = current_user.microposts.find(params[:id])
rescue
redirect_to root_url
end
至此删除功能实现。