attr_accessible(*attributes)
との違いは何ですかattr_protected(*attributes)
? 例があると嬉しいです。
多くの開発者がモデルでこれらを使用しているのを目にします。違いを Google で検索しましたが、正確にはわかりません。さまざまなシナリオでの重要性と必要性は何ですか?
ベストアンサー1
attr_accessible
(ドキュメンテーション)は「指定された属性はアクセス可能で、その他はすべて保護されている」と言っている(ホワイトリスト。
一方
attr_protected
(ドキュメンテーション)は「指定された属性は保護されており、他のすべての属性はアクセス可能です」と言っている(ブラックリスト。
あ保護された属性明示的に変更できるもの(例:属性=model.update_attributes
) であり、一括代入 (またはを使用して属性を に渡すなど)によって更新することはできませんnew
。一括代入によって保護された属性を更新しようとしたときの動作は、設定によって異なりますmass_assignment_sanitizer
(以下の更新を参照)。
典型的な例としては、User
モデルに属性がある場合is_admin
、その属性を保護して、任意のユーザーを管理者として設定できるフォームの送信を防ぐことができます。
例:
class User < ActiveRecord::Base
# explicitly protect is_admin, any new attributes added to the model
# in future will be unprotected so we need to remember to come back
# and add any other sensitive attributes here in the future
attr_protected :is_admin
end
と比べて:
class User < ActiveRecord::Base
# explicitly unprotect name and bio, any new attributes added to the model
# in the future will need to be listed here if we want them to be accessible
attr_accessible :name, :bio
end
ここで、is_admin
属性が保護されていると仮定します。
> u = User.find_by_name('mikej')
> u.is_admin?
false
> u.update_attributes(:name => 'new name', :is_admin => true)
> u.is_admin?
false
> u.name
"new name"
> u.is_admin = true # setting it explicitly
> u.save
> u.is_admin?
true
更新: Railsの後のバージョンでは、大量割り当てサニタイザー保護された属性を一括割り当てによって更新しようとしたときの動作を制御します。Rails 3.2 以降では、設定でこれを制御できますmass_assignment_sanitizer
。デフォルトでは、試行をログに記録してコードの実行を続行しますが、開発用の標準環境設定では、:strict
保護された属性を更新しようとしたときに例外が発生するように設定されています。