Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails RubyonRails-路由到当前用户';s posts路径_Ruby On Rails - Fatal编程技术网

Ruby on rails RubyonRails-路由到当前用户';s posts路径

Ruby on rails RubyonRails-路由到当前用户';s posts路径,ruby-on-rails,Ruby On Rails,我希望能够显示只属于当前用户的帖子。 以下是我目前的做法 控制器 def index @user = User.find(params[:id]) @posts = @user.posts; end 看法 即使在此用户id下有posts记录,我也会出现以下错误 ActiveRecord::RecordNotFound in PostsController#index Couldn't find User without an ID 这里缺少什么?您需要为此设置一个嵌套资源 在您的r

我希望能够显示只属于当前用户的帖子。
以下是我目前的做法

控制器

def index
  @user = User.find(params[:id])
  @posts = @user.posts;
end 
看法

即使在此用户id下有posts记录,我也会出现以下错误

ActiveRecord::RecordNotFound in PostsController#index
Couldn't find User without an ID

这里缺少什么?

您需要为此设置一个嵌套资源

在您的routes.rb中

resources :users do
  resources :posts
end
然后在您的视图中,您可以将用户传递到如下路径:

  • 如果使用
    @user
    正确调用路径,则
    posts\u controller.rb
    索引操作将已经设置了
    @user\u id

    更多信息请点击此处:

    ActiveRecord::RecordNotFound in PostsController#index
    Couldn't find User without an ID
    
    resources :users do
      resources :posts
    end