【Rails学习笔记】用户微博【下】

上节初步实现了用户发微博的功能,现在增加一个动态列表 。


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

至此删除功能实现。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值