LoginSignup
2
3

More than 5 years have passed since last update.

Rails のルーティングで複数の concerns 適用の書き方メモ

Last updated at Posted at 2016-09-30
    resources :blogs do
      concerns :likable, likable_type: 'Blog'
      concerns :commentable, commentable_type: 'Blog'
    end

って書いていたが、 concerns は複数のシンボルを引数に取れるので

    resources :blogs do
      concerns :likable, :commentable, target_model: 'Blog'
    end

でよい。パラメータを渡すときは DRY にすることができますね

下記で、複数を受け取っていることがわかります

rails/rails/blob/v5.0.0/actionpack/lib/action_dispatch/routing/mapper.rb#L2026-L2030
        def concerns(*args)
          options = args.extract_options!
          args.flatten.each do |name|
            if concern = @concerns[name]
              concern.call(self, options)

      concerns :commentable, commentable_type: 'Blog'

ちなみにこの Blog の部分、もちろん Blog.to_s とか(もしくは string ではなく class の Blog のまま)で渡したかったのですが、 routes の時点ではモデルのロードが終わっていないようで、できませんでした

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3