2017-04-27 51 views
1

是否有可能在同一視圖上有兩個。與他們做不同的搜索?Rails:是否有可能在同一個視圖上有兩個不同的循環?

例如,如果我想顯示由一個特定用戶所做的所有帖子。我想有以下行爲在我的用戶控制:

def show 
    @user = User.find(params[:id]) 
    @posts = @user.posts 
end 

然後在視圖中我會有:

- @posts.each do |post| 
    =post.title 

然後如果我想在同一個視圖中顯示其他用戶的帖子。使用上述不會工作作爲其唯一的搜索特定用戶帖子。

然後我會創建一個新的操作? 類似以下內容:

def showAll 
    @user = User.find(params[:id]) 
    @posts = Post.where(:attribute => value).order("created_at DESC") 
end 

然後回到視圖頁面我會用這一個是像SHOWALL動作與另一each.do:

- @posts.each do |post| 
    =post.title 

我將如何實現這一目標?這是使用操作的正確方法嗎?

+0

'@posts =(@user == CURRENT_USER)? @ user.posts:Post.where(:attribute => value).order(「created_at DESC」)'在你的show action中試試這個 –

+0

可能有某種類型的用戶想要顯示數據的連接。我不是逐行找到單獨的用戶,而是首先通過它們的公共鏈接(例如User.where(something:true))來查找用戶,然後遍歷它。 – bkunzi01

回答

1

是的,你可以做的是,在同樣的動作本身

def show 
    @posts = current_user.posts 
    @other_posts = Post.where(:attribute => value).order("created_at DESC") 
    # OR 
    # @other_posts = Post.where.not(id: @posts).order("created_at DESC") 
end 

然後你可以遍歷他們鑑於

%h2 Your posts 
- @posts.each do |post| 
    = post.title 

%h2 Posts from other users 
- @other_posts.each do |post| 
    = post.title 
相關問題