2015-09-29 62 views
0

我正在嘗試做一些類似Instagram的事情,在那裏你可以看到你只關注人的圖像。用戶可以關注另一個用戶並創建新帖子。如何獲得只有人跟帖的帖子的時間表

這是我在用戶控制器中關注和取消關注的內容。

def following 
    @user = User.find(params[:id]) 
    current_user.mark_as_following @user 

    respond_to do |format| 
    format.html {redirect_to @user} 
    format.js 
    end 
end 

def unfollow 
    @user = User.find(params[:id]) 
    @user.unmark :following, :by => current_user 

    respond_to do |format| 
    format.html {redirect_to @user} 
    format.js 
    end 
end 

這裏是我的我的帖子控制器

class PostsController < ApplicationController 
    load_and_authorize_resource 
    def show 
     @post = Post.find(params[:id]) 
    end 

    def new 
     @post = Post.new 
    end 

    def create 
     @post.user_id = current_user.id 
     if @post.save 
      redirect_to @post 
     else 
      render :new 
     end 
    end 

    def edit 
     @post = Post.find(params[:id]) 
    end 

    def update 
     @post = Post.find(params[:id]) 
     if @post.update_attributes(update_params) 
      redirect_to @post 
     else 
      render :edit 
     end 
    end 

    private 
     def update_params 
      params.require(:post).permit(:caption, :image) 
     end 

     def create_params 
      params.require(:post).permit(:caption, :user_id, :image) 
     end 
end 

回答

1

,你可以創建一個這樣

class FollowingPostsController < ApplicationController 

    def index 
     @posts = current_user.following_posts 
    end 
end 

,並在您的用戶模型中的控制器

class User < ActiveRecord::Base 
    def following_posts 
     #assuming that following_users returns the list of following users 
     self.following_users.map{ |user| user.posts }.flatten(1) 
    end 
end 

或者你也可以得到帖子列表:

Post.where(user_id: self.following_users.ids) 
+0

您可以使用聯接來獲取一個查詢中的帖子。您在這裏建議的結果會爲您關注的每個用戶查詢。 – Mischa

+0

但加入會返回一個用戶列表,而不是帖子列表 –

+0

您必須以'Post'開始,然後加入您需要的用戶表。我不知道他的模型/屬性名稱,但類似於:'Post.joins(:user,:user_followings).where(:follower_id => current_user.id)'。這將在一個查詢中返回您需要的帖子。 – Mischa

相關問題