我一直在嘗試在 Rails 中顯示用戶和帖子表之間的關聯。我的問題是當用戶登錄時,他/她應該能夠在我的反應前端看到他們自己的所有帖子。但是,我的前端請求只能獲取與我當前用戶相關的第一條記錄。這是我向后端發送獲取請求以獲取與用戶 ID 相關的帖子的地方。
export default function Profile({currentUser}){
const [posts, setPosts] = useState([])
useEffect(() => {
fetch(`/posts/${currentUser.id}`)
.then((r) =>{
if(r.ok){
r.json().then((posts)=>setPosts(posts))
}
})
}, [])
這就是我的路線的樣子
get '/posts/:id', to: "posts#show"
最后,這是我的后端獲取與登錄用戶相關的博客文章的地方。
def show
posts = Post.find_by(id:params[:id])
render json: posts, include: :user
end
我知道 find_by 方法只獲取滿足條件的第一條記錄。我也嘗試使用user.Post.all來獲取記錄。有什么建議嗎?
uj5u.com熱心網友回復:
目前,您的請求將回傳您Post的. 我認為這不是你想要的...... :):idcurrentUser
我猜你想要類似的東西:
def show
posts = User.find(params[:id]).posts # Hint: find_by(id: id) == find(id)
...
end
uj5u.com熱心網友回復:
您正在以一種奇怪的方式使用路由、控制器和請求。
問題
我假設您共享的控制器是 Posts 控制器,這意味著您需要Index操作,而不是 Show 操作。當您想要呈現單個 Post 時使用Show操作。
您將 傳遞currentUser.id給后端作為posts/:id. 恐怕這是不對的,因為它posts/:id指的是 Post id 而不是 User id。除此之外,您的后端應該在用戶登錄時已經知道它。
您的授權 gem 應該有一種訪問當前用戶的方法。例如,devise gem 暴露了一個呼叫current_user所有控制器的方法。
解決方案
這意味著你的路線應該是get '/posts', to: "posts#index"
你的控制器應該是
def index
posts = current_user.posts # current_user or your way to access the user
render json: posts, include: :user
end
你的 React 前端應該是
export default function Profile({currentUser}){
const [posts, setPosts] = useState([])
useEffect(() => {
fetch(`/posts`)
.then((r) =>{
if(r.ok){
r.json().then((posts)=>setPosts(posts))
}
})
}, [])
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/482374.html
上一篇:JSON::ParserError:RailsRspec上的''處出現意外標記
下一篇:匹配函式Ruby的正則運算式
