【问题标题】:Should there be a direct resource route for any nested route?任何嵌套路由都应该有直接资源路由吗?
【发布时间】:2015-01-27 03:10:19
【问题描述】:

我有一个类用户和一个类任务。我的任务资源路由嵌套在用户资源中,任务属于_to 用户和用户有_many 任务。

resources :users, except: [:new, :edit] do
  resources :tasks, except: [:new, :edit] 
end

在我的 rspec“请求”测试中,我尝试向关联用户发布一项新任务,但看起来它最终试图直接命中 /tasks 路由,但它最终没有找到。如果我的路由文件如下所示,则测试通过:

  resources :users, except: [:new, :edit] do
    resources :tasks, except: [:new, :edit] 
  end

  resources :tasks, except: [:new, :edit] 

测试看起来像这样(有一个before(:each) 创建一个@user1):

  describe "POST /users/1/tasks" do
    it "creates a new task for user1" do
        post user_tasks_path(@user1, task: {description: "post new task", due_date: "2/1/15", user_id: @user1.id})
        expect(response).to have_http_status(201)
        puts response.body
    end
  end

【问题讨论】:

  • rake routes 打印出来的是什么?

标签: ruby-on-rails rspec rails-api


【解决方案1】:

不,嵌套资源不是必须的。

现在,关于您的规格。我不确定它是否试图到达/tasks,但请注意post 方法的语法:

post(action, *args)

也就是说,你应该这样做:

post(user_tasks_path(@user1), task: {})

代替:

post(user_tasks_path(@user1, task: {}))

HTH。

【讨论】:

  • 实际上,这仅在我的路由文件具有嵌套和显式路径时才有效。如果我只有嵌套的,我不会得到 TasksController 的方法 task_url。有什么想法吗?
  • 本应如此。如果你只有嵌套的[user, task] 路由,你只会得到user_task* 助手。您可以使用rake routes 命令检查您的路线和助手。
  • 我意识到为什么会出现这个错误。在任务控制器的创建操作中,它有: if (at)task.save render json: (at)task, status: :created, location: (at)task 我认为它正在路由到“task_url”。如果我将 location: (at)task 更改为像“location: users/#{(at)user.id}/tasks/#{(at)task.id}”这样的插值字符串,它可以工作! (注意:将 (at) 替换为 at 符号)
猜你喜欢
  • 2019-04-20
  • 2013-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多