Ruby on rails Rails没有路由匹配,在多态新操作测试中
这是我第一次使用多态关联,因此错误可能很小 从一开始,模型:Ruby on rails Rails没有路由匹配,在多态新操作测试中,ruby-on-rails,rspec,polymorphic-associations,Ruby On Rails,Rspec,Polymorphic Associations,这是我第一次使用多态关联,因此错误可能很小 从一开始,模型: class Comment < ActiveRecord::Base belongs_to :comment_owner, polymorphic: true end class Announcement < ActiveRecord::Base has_many :comments, as: :comment_owner end 注释控制器新操作: class CommentsController <
class Comment < ActiveRecord::Base
belongs_to :comment_owner, polymorphic: true
end
class Announcement < ActiveRecord::Base
has_many :comments, as: :comment_owner
end
注释控制器新操作:
class CommentsController < ApplicationController
before_filter :find_comment_owner
def new
@comment = @comment_owner.comments.new
end
private
def find_comment_owner
# Switch comment_owner_string into constant
@klass = params[:comment_owner_type].capitalize.constantize
@comment_owner = @klass.find(params[:comment_owner_id])
end
end
我的错误是:
ActionController::UrlGenerationError:
No route matches {:action=>"new", :comment_owner_id=>"27", :comment_owner_type=>"Announcement", :controller=>"comments"}
我的想法是,路由应该是,操作是建立在这个基础上的,comment_owner的参数此时应该没有意义,因为它在comments controller中找不到新操作 您可以检查生成的路由表单
http://localhost:3000/rails/info/routes
new_announcement_comment_path GET/announcements/:announcement_id/comments/new(:format)comments#new
这是我的新公告注释路线您使用此链接吗?你到底想要什么?我的问题是测试不正确。目前我不使用这个链接,我想先测试评论和操作。当我尝试从comments controller测试简单的新操作时,我得到了一个错误,我认为您需要使用多态关联名称,并让Rails处理匹配的操作。尝试get:new,comment\u owner:dummy\u post
describe 'New action test' do
let(:dummy_post) do
create(:announcement)
end
before :each do
get :new, comment_owner_id: dummy_post.id, comment_owner_type: dummy_post.class.name
end
it 'return redirect http status' do
expect(response).to have_http_status(:success)
end
end
ActionController::UrlGenerationError:
No route matches {:action=>"new", :comment_owner_id=>"27", :comment_owner_type=>"Announcement", :controller=>"comments"}