我在Rails 4:
上使用继承的资源宝石有问题每当我尝试创建一个范围向用户范围的新项目时,我会收到此错误:
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&lt;senasitedResources ::基础 wonds_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
我找到了答案。
在我的代码中,我正在循环通过各种项目来创建快捷链接
在Active Resource中创建一个新模型时,它使用:current_user.project.build(),这为没有ID的用户添加了一个未保存的实体。当我循环创建项目链接时,Rails会抱怨,因为它无法创建指向没有ID的未保存实体的链接。