上节初步实现了用户发微博的功能,现在增加一个动态列表 。
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>
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 %>
<% if current_user?(feed_item.user) %> <%= link_to "delete", feed_item, method: :delete, data: { confirm: "You sure?" }, title: feed_item.content %> <% end %>
def destroy @micropost.destroy redirect_to root_url end
加入一个私有方法:
def correct_user @micropost = current_user.microposts.find(params[:id]) rescue redirect_to root_url end