Ruby on rails with React Frontend(显示关联数据)

Ruby on rails with React Frontend(Displaying associated data)

我一直在尝试显示 rails 中用户和帖子表之间的关联。我的问题是,当用户登录时,he/she 应该能够在我的反应前端看到他们自己的所有帖子。但是,我的前端请求只能获取与我当前用户相关的第一条记录。 这是我向后端发送获取请求以获取与用户 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 来获取记录。有什么建议吗?

目前您的请求将 return PostcurrentUser:id。我认为这不是您想要的...:)

我猜你想要这样的东西:

def show
   posts = User.find(params[:id]).posts # Hint: find_by(id: id) == find(id)
   ...
end

您正在以一种奇怪的方式使用路由、控制器和请求。

问题

我假设您共享的控制器是 Posts 控制器,这意味着您需要 Index 操作,而不是 Show 操作。当您想要呈现单个 Post.

时,使用 Show 操作

您将 currentUser.id 作为 posts/:id 传递给后端。恐怕这是不对的,因为 posts/:id 指的是 Post id 而不是用户 id。除此之外,您的后端应该已经知道用户已登录。

您的授权 gem 应该可以访问当前用户。例如,设计 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 front-end 应该是

export default function Profile({currentUser}){

    const [posts, setPosts] = useState([])

     useEffect(() => {
        fetch(`/posts`)
        .then((r) =>{
          if(r.ok){
              r.json().then((posts)=>setPosts(posts))
          }
      })
    }, [])