0

我在 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 < InheritedResources::Base respond_to :html, :json

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
4

1 回答 1

1

我找到了答案。

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

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

于 2014-01-24T00:38:19.630 回答