【问题标题】:Inherited Resources + Devise User, #new missing required keys: [:id]继承的资源 + 设计用户,#new 缺少必需的键:[:id]
【发布时间】:2014-01-22 13:48:24
【问题描述】:

我在使用 rails 4 上的 Inherited Resource Gem 时遇到问题:

每当我尝试创建一个仅限于用户的新项目时,我都会收到此错误:

 Failure/Error: visit new_project_path
 ActionView::Template::Error:
   No route matches {:id=>#<Project id: nil, user_id: 32568, name: "", created_at: nil, updated_at: nil>} missing required keys: [:id]

据我了解,新操作不需要 ID,它唯一需要的是访问我通过 begin_of_association_chain 方法提供的用户。

有人知道为什么会这样吗?我确定我错过了一些简单的东西?

控制器:

类 ProjectsController

before_filter :authenticate_user!

protected
  def begin_of_association_chain
    #provided by devise
    current_user 
  end

private
  def permitted_params
    {:project => params.fetch(:project, {}).permit(:email, :name, :destination_ids => [])}
  end
end

Rspec 测试:

require 'spec_helper'

include Warden::Test::Helpers

describe "the signed in user" do

  before :each do
    @user = FactoryGirl.create(:confirmed_user)
    login_as(@user, scope: :user)
  end

  describe "with new project" do

    before :each do
      @project = FactoryGirl.attributes_for(:project)
      visit new_project_path
      fill_in "project_name", with: @project[:name]
    end

    it "can create" do
      expect { click_button('Create Project') }.to change(Project, :count).by(1)
    end

  end

end

查看:

<div class="row">
 <div class="large-12 columns">
  <%= form_for(@project) do |f| %>

    <% if @project.errors.any? %>
      <div data-alert class="alert-box alert"><%= pluralize(@project.errors.count, "error") %> prohibited this source from being saved:</div>
    <% end %>

    <%= f.text_field_block :name, placeholder: "Your project's name", maxlength: 500 %>

    <hr>

    <div class="row">
     <div class="large-5 columns">
        <%= f.submit class: "button tiny" %> <%= link_to 'Back', :back, class: "button secondary tiny" %>
     </div>
    </div>
  <% end %>
 </div>
</div>

路线:

projects POST     /projects(.:format)           projects#create
new_project GET   /projects/new(.:format)       projects#new
edit_project GET  /projects/:id/edit(.:format)  projects#edit
project GET       /projects/:id(.:format)       projects#show
PATCH             /projects/:id(.:format)       projects#update
PUT               /projects/:id(.:format)       projects#update
DELETE            /projects/:id(.:format)       projects#destroy

【问题讨论】:

    标签: ruby rspec devise ruby-on-rails-4 inherited-resources


    【解决方案1】:

    我找到了答案。

    在我的代码中,我循环各个项目以创建快捷链接

    当您创建它使用的新模型时,在活动资源中:current_user.project.build() 这向我的用户添加了一个未保存的实体,它没有 id。当我循环创建项目链接时,rails 抱怨,因为它无法创建指向没有 id 的未保存实体的链接。

    【讨论】:

    • 那你是怎么解决的?
    • 基本上,我的对象图中有一个未保存的实体(例如,一个帐户有一个未保存的附加用户)。因此,一旦我发现将它放在那里并停止它就解决了我的问题。可悲的是我不记得确切的细节,也许如果你发布一个包含一些细节的问题,我可以看看我是否可以帮忙?另请注意,已不再处理 InheritedResources。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多