我在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&lt; InheritedResources ::基地 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
答案 0 :(得分:1)
我找到了答案。
在我的代码中,我循环遍历各种项目以创建快捷方式链接
在创建新模型时,在活动资源中,它使用:current_user.project.build()这会向我的用户添加一个没有id的未保存实体。当我循环创建项目链接时,rails抱怨,因为它无法创建一个没有id的未保存实体的链接。