所以我试图找到在同一张图片下发表评论的所有用户。
在psql终端中,我写了这个,它为我提供了我需要的所有信息:
select * from users
inner join comments on users.id = comments.user_id
inner join media on media.id = comments.media_id
where media_id = 1
现在我在Rails中正在这样做:
@users = User.joins(:comments, :media).where(media_id = @medium.id)
我认为哪个应该有效。
但是当我尝试在我的视图中打印出@users
中的所有用户名时,会抛出此错误:
Association named 'media' was not found on User; perhaps you misspelled it?
我在这里做错了加入条款吗?
DB Schema:
create_table "media", force: true do |t|
# Unrelevant columns
t.integer "user_id"
end
add_index "media", ["user_id"], name: "index_media_on_user_id", using: :btree
create_table "comments", force: true do |t|
# Unrelevant columns
t.integer "user_id", null: false
t.integer "media_id", null: false
end
add_index "comments", ["media_id"], name: "index_posts_on_media_id", using: :btree
add_index "comments", ["user_id"], name: "index_posts_on_user_id", using: :btree
create_table "users", force: true do |t|
t.string "name", default: "", null: false
end
答案 0 :(得分:2)
由于media
与comments
而不是users
直接相关,您应该:{/ p>
@users = User.joins(comments: :media).where(comments: {media_id: @medium.id})