13

与えられたルート:

Example::Application.routes.draw do
  concern :commentable do
    resources :comments
  end

  resources :articles, concerns: :commentable

  resources :forums do
    resources :forum_topics, concerns: :commentable
  end
end

そしてモデル:

class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
end

コメントを編集または追加するときは、「コメント可能」オブジェクトに戻る必要があります。ただし、次の問題があります。

1)親オブジェクトredirect_tocomments_controller.rb応じて異なる

2)ビューの参照も異なります

= simple_form_for comment do |form|

commentこのリソースのビューとコントローラーを共有する実用的な方法はありますか?

4

2 に答える 2

18

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
于 2015-02-11T23:07:15.880 に答える
12

次のような before フィルターで親を見つけることができます。

コメント_コントローラー.rb

before_filter: find_parent

def find_parent
  params.each do |name, value|
    if name =~ /(.+)_id$/
      @parent = $1.classify.constantize.find(value)
    end
  end
end

これで、親のタイプに応じて、リダイレクトしたり、好きなことをしたりできます。

たとえば、ビューでは次のようになります。

= simple_form_for [@parent, comment] do |form|

またはコントローラーで

コメント_コントローラー.rb

redirect_to @parent # redirect to the show page of the commentable.
于 2013-05-07T09:51:53.420 に答える