我是rails的新手,但是在我跟着michael hartl rails之后,我想知道如何查看你关注的人的帖子?
用户模型
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :posts, dependent: :destroy
has_many :active_relationships, class_name: "Relationship",
foreign_key: "follower_id",
dependent: :destroy
has_many :passive_relationships, class_name: "Relationship",
foreign_key: "followed_id",
dependent: :destroy
has_many :following, through: :active_relationships, source: :followed
has_many :followers, through: :passive_relationships, source: :follower
def feed
following_ids = "SELECT followed_id FROM relationships
WHERE follower_id = :user_id"
Post.where("user_id IN (#{following_ids})
OR user_id = :user_id", user_id: id) end
def follow(other)
active_relationships.create(followed_id: other.id) end def unfollow(other)
active_relationships.find_by(followed_id: other.id).destroy end def following?(other)
following.include?(other) end
关系控制器
class RelationshipsController < ApplicationController
before_filter :authenticate_user!
def create
user = User.find(params[:followed_id])
current_user.follow(user)
respond_to do |format|
format.html { redirect_to :back }
format.js
end
end
def destroy
user = Relationship.find(params[:id]).followed
current_user.unfollow(user)
respond_to do |format|
format.html { redirect_to :back }
format.js
end
end
end
关系模型
class Relationship < ActiveRecord::Base
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
validates :follower_id, presence: true
validates :followed_id, presence: true
end
所以我希望代码是什么?我试过current_user.followed_id.posts
但是没有工作......
答案 0 :(得分:0)
我相信你已经在代码中找到了答案。
User#feed
方法可以让您这样做:
user = User.first
user.feed # => [<posts from the users that you follow>]