我一直在尝试在rails中显示用户和posts表之间的关联。我的问题是,当用户登录时,他/她应该能够在我的react前端看到他们自己的所有帖子。然而,我的前端请求只能获取与我当前用户相关的第一条记录。这是我向我的后端发送获取请求以获取与用户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
来获取记录。有什么建议吗?
2条答案
按热度按时间0wi1tuuw1#
目前,您的请求将返回
Post
和currentUser
的:id
。我觉得这不是你想要的。:)我猜你想要的是:
b91juud32#
你正在以一种奇怪的方式使用路由、控制器和请求。
问题
我假设你共享的控制器是Posts控制器,这意味着你需要Index操作,而不是Show操作。Show操作用于渲染单个Post。
将
currentUser.id
作为posts/:id
传递给后端。恐怕这是不正确的,因为posts/:id
指的是一个帖子ID而不是用户ID。除此之外,你的后端应该已经知道用户,因为它是登录。您的授权gem应该有一种访问当前User的方法。例如,devise gem向所有控制器公开了一个名为
current_user
的方法。解决方案
这意味着你的路线应该是
get '/posts', to: "posts#index"
您的控制器应
你的React前端应该