我一直在引用this rails教程,尝试创建一个Feed,其中只有属于已接受我朋友请求的用户的文章会显示在我的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 %>
答案 0 :(得分:1)
对于你的情况我认为密钥在这里WHERE(user_id =:user_id AND accepted = true),我从友谊架构中获得了接受的字段。
def feed
friend_ids = "SELECT friend_id FROM friendships
WHERE (user_id = :user_id AND accepted = 't')"
Article.where("user_id IN (#{friend_ids})
OR user_id = :user_id", user_id: id)
end