LoginSignup
34
30

More than 5 years have passed since last update.

Grape での mass assignment 対策

Last updated at Posted at 2013-02-23

API 作成用のフレームワークである Grape で mass assignment 対策するにはいくつかありますが、そのうちで Rails 4 の strong_parameters を使用する方法、Grape 自身の declared を使用する方法を紹介します。

対象

  • Grape 0.3.0
  • Rails 3.2.12
  • strong_parameters 0.2.0

Rails 4 の strong_parameters を使用する方法

strong_parameters は Rails 4 で mass assignment 対策のためにデフォルトで追加される RubyGem です。使用方法については以下のサイトが参考になるでしょう。

Grape でも params があるので、Rails と同じように params.permit(・・・ と strong_parametes を使用すると怒られます。これは Rails の params が ActionController::Parameters である一方で、Grape のそれは Hashie::Mash であり、strong_parameters が前者を期待しているからです。
そこで README に書かれているように ActionController::Parameters でラップしてあげるとうまくいきます。

Rails 4 で scaffold すると controller に 〜params と Private メソッドが作成されるように、Grape でも Helper メソッドにしておくのがいいと思います。

articles.rb
module Api
  class Articles < Grape::API
    helpers do
      def article_params
        ActionController::Parameters.new(params).permit(:title, :content, :published)
      end
    end
  end
end

Grape 自身の declared を使用する方法

Grape 自体も declared というメソッドを用意しています。これは API の定義時に指定する params に基づいて、そこで指定されていないものは落とすという一部 strong_parameters とよく似た動作をしています。

articles.rb
# (略)
params do
  requires :title, type: String
  requires :content, type: String
  optional :published, type: Boolean
end
post do
  article = Article.new(declared(params, include_missing: false))
  # (略)
end

Rails アプリの中で組み込んで使うことが多いので、strong_parameters を使用しています。

参考

34
30
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
34
30