Ruby on Rails with React Frontend(与React相关的数据)

piah890a  于 12个月前  发布在  Ruby
关注(0)|答案(2)|浏览(73)

我一直在尝试在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来获取记录。有什么建议吗?

0wi1tuuw

0wi1tuuw1#

目前,您的请求将返回PostcurrentUser:id。我觉得这不是你想要的。:)
我猜你想要的是:

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

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"
您的控制器应

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))
          }
      })
    }, [])

相关问题