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 %>