2013-05-03 42 views
0

我正在創建一個Twitter副本,現在我試圖從所有你關注的用戶那裏獲取所有帖子,然後將它們顯示在主頁上頁。我之前在PHP中做過這個,但我是RoR的新手,所以我可能會試圖以錯誤的方式做到這一點。Ruby on Rails:將帖子按入一個散列,然後顯示它們

用戶有許多訂閱 和訂閱屬於用戶

用戶有很多文章 和專屬於用戶

這是我到目前爲止有:

session_controller.rb

def get_posts 
    @sub = @current_user.subscriptions.first 
    Post.where("user_id = ?", @sub.following_id).find_each do |tweet| 
    render partial: 'shared/tweet', locals: {tweet: tweet} 
    end 
end 

我知道。首先只獲得第一次訂閱,但我想試着弄出一些東西。

home.html.erb

<table> 
    <tr> 
     <th>Username</th> 
     <th>Tweet</th> 
    </tr> 
    <%= yield %> 
</table> 

_tweet.html.erb

<div class="tweet"> 
    <td>Username here somehow</td> 
    <td><%= tweet.content %></td> 
</div> 

但現在沒有什麼是即將在桌上。所以,我在做什麼錯誤? (我在做任何事情的權利呢?)

+0

你爲什麼要插入一個div內的TD? – giorgian 2013-05-03 14:05:42

+0

哦..忘了改變了..從一開始就沒有使用表格。 – Alexander 2013-05-03 14:07:42

+0

你在哪裏使用'get_posts'輔助方法? – cortex 2013-05-03 14:09:11

回答

2

試試這個:

session_controller.rb

def get_posts 
    @sub = @current_user.subscriptions.first 
    @tweets = Post.where("user_id = ?", @sub.following_id) 
end 

home.html.erb

<table> 
    <thead> 
    <tr> 
     <th>Username</th> 
     <th>Tweet</th> 
    </tr> 
    </thead> 
    <tbody> 
    <% @tweets.each do |tweet| %> 
    <%= render 'shared/tweet', tweet: tweet %> 
    <% end %> 
    </tbody> 
</table> 

_tweet。 html.erb

<tr class="tweet"> 
    <td><%= tweet.user.name %></td> # Not sure 
    <td><%= tweet.content %></td> 
</tr> 

編輯:

爲了讓所有的鳴叫所有subscritions:

following_ids = @current_user.subscriptions.map(&:following_id) 
@tweets = Post.where(user_id: following_ids) 
相關問題