1
我一直在参考this rails教程,试图创建一个只有属于已接受我的好友请求的用户的文章出现在我的提要中的Feed。然而,我有一个不同的模式和用户模型从教程(我有一个额外的步骤,朋友请求正在等待接受)。在我的用户模型中的下面的方法不会过滤掉没有被接受的友谊,因此未经证实的朋友的文章正在出现我的馈送,这不是我想要的。自定义Feed只显示关注用户的文章
user.rb
has_many :friendships
has_many :received_friendships, class_name: "Friendship", foreign_key: "friend_id"
has_many :active_friends, -> { where(friendships: { accepted: true}) }, through: :friendships, source: :friend
has_many :received_friends, -> { where(friendships: { accepted: true}) }, through: :received_friendships, source: :user
has_many :pending_friends, -> { where(friendships: { accepted: false}) }, through: :friendships, source: :friend
has_many :requested_friendships, -> { where(friendships: { accepted: false}) }, through: :received_friendships, source: :user
def feed
friend_ids = "SELECT friend_id FROM friendships
WHERE user_id = :user_id"
Article.where("user_id IN (#{friend_ids})
OR user_id = :user_id", user_id: id)
end
schema.rb
create_table "friendships", force: :cascade do |t|
t.integer "user_id"
t.integer "friend_id"
t.boolean "accepted", default: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
页控制器
def home
@feed = current_user.feed.all
end
home.html.erb
<%= render @feed %>