这是我第一次使用多态关联,因此错误可能是微不足道的。
从一开始,模特:
class Comment < ActiveRecord::Base
belongs_to :comment_owner, polymorphic: true
end
class Announcement < ActiveRecord::Base
has_many :comments, as: :comment_owner
end
路线:
resources :announcements do
resources :comments
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
最后测试:
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"}
我的想法,路线应该是fine,行动是建立在这个tutorial上的,对于comment_owner的params目前没有任何意义,因为它无法在评论中找到新动作控制器。