Rails 4 では、懸念事項にオプションを渡すことができます。したがって、これを行う場合:
# routes.rb
concern :commentable do |options|
resources :comments, options
end
resources :articles do
concerns :commentable, commentable_type: 'Article'
end
次に、次rake routes
のようなルートが表示されます
POST /articles/:id/comments, {commentable_type: 'Article'}
これは、リクエストが安全に保つために設定しようとするものをすべて上書きします。次に、CommentsController で次のようにします。
# comments_controller.rb
class CommentsController < ApplicationController
before_filter :set_commentable, only: [:index, :create]
def create
@comment = Comment.create!(commentable: @commentable)
respond_with @comment
end
private
def set_commentable
commentable_id = params["#{params[:commentable_type].underscore}_id"]
@commentable = params[:commentable_type].constantize.find(commentable_id)
end
end
このようなコントローラーを rspec でテストする 1 つの方法は次のとおりです。
require 'rails_helper'
describe CommentsController do
let(:article) { create(:article) }
[:article].each do |commentable|
it "creates comments for #{commentable.to_s.pluralize} " do
obj = send(commentable)
options = {}
options["#{commentable.to_s}_id"] = obj.id
options["commentable_type".to_sym] = commentable.to_s.camelize
options[:comment] = attributes_for(:comment)
post :create, options
expect(obj.comments).to eq [Comment.all.last]
end
end
end