目前,我有粉丝可以跟随艺术家。现在,我想展示艺术家的微博艺术家的艺术家是跟随。
我想通过created_at对艺术家的微博进行排序,因为他们是创建的。
<% @fan.artists.each do |artist| %>
<% artist.artist_microposts.sort_by{ |micropost| micropost.created_at }.each do |micropost| %>
<%= micropost.content %>
<% end %>
<% end %>它是按created_at进行排序的,但是因为它首先遍历每个艺术家,它显示属于一个艺术家的所有微格,然后显示属于下一个艺术家的所有镜像,等等。
我希望它更像一个时间线,像推特,在他们进来的时候显示微博。
发布于 2015-02-15 19:43:35
我能够通过在fans、artists和artist_microposts之间创建一个连接表来实现这一点。然后我做了
<% @fan.artist_microposts.sort_by{ |micropost| micropost.id }.each do |micropost| %>
<%= micropost.content %>
<% end %>效果很好。
发布于 2015-02-09 00:35:43
这不是您实现此功能的方式。如果您想在新的tweet到达时更新时间线,那么您需要使用Jquery监听更改。看看这个[http://railscasts.com/episodes/229-polling-for-changes][1],它将向您展示如何实现您想要的特性。
提示:不要按created_at排序,这是一种糟糕的做法,因为create_at不是索引,而且速度会更慢。相反,按id排序,它会自动递增和索引。
artist.artist_microposts.order('id DESC')发布于 2015-02-09 13:04:00
我能够通过先获取艺术家ids,然后选择与这些艺术家相关的帖子来解决问题。
irb(main):019:0> fan = Fan.first
#<Fan id: 1, name: "Tony">
irb(main):020:0> ids = fan.artists.pluck(:id)
#=> [1, 2]
irb(main):022:0> posts = Post.where(:artist_id => ids).order("created_at DESC")
#=> #<ActiveRecord::Relation [
#<Post id: 3, text: "Third Post", artist_id: 1, created_at: "2015-02-10 12:54:32">,
#<Post id: 2, text: "Second Post", artist_id: 2, created_at: "2015-02-09 12:53:14">,
#<Post id: 1, text: "First Post", artist_id: 1, created_at: "2015-02-08 12:52:51"> ]>https://stackoverflow.com/questions/28400312
复制相似问题