2

簡単な部分:

保護された属性を持つモデルがあり、管理者のみがアクセスできるアクション、すべての属性を強制的に割り当てる方法があるため、次のようなことをする必要はありません:

@post = Post.find(params[:id])
if params[:post].is_a?(Hash) && params[:post][:published]
  @post.published = params[:post].delete(:published) # delete is to skip warning about protected attribute assignment in update_attributes
end
if @order.update_attributes(params[:post])
  …

難しい部分:

多くの保護された属性と複数のタイプのユーザーを持つモデルがあり、保護されていない属性のみを割り当てることができるモデル、保護された属性の一部のみを変更できるモデル、すべての属性を変更できるモデルがあります。この場合、車輪を再発明することなく、小さくて読みやすいコードを書くにはどうすればよいでしょうか?

4

1 に答える 1

0

さて、私はあなたがそれを行うための2つの方法を考えることができます. まず、コントローラーで: これはpermitted_to?、ユーザーがその属性を変更できるかどうかを確認するメソッドがあることを前提としています。

if params[:post]
  params[:post].each_pair do |key, value|
    @post.send("#{key.to_s}=", value) if @current_user.permitted_to?(:update_attribute, :post, key.to_sym)
  end
  @post.save
end

クラスのプロパティを変更するため、おそらく最良の方法ではない別の方法です。これは、モデルのすべてのインスタンスに影響することを意味します。

attr_accessibleとにかく、属性を制限するために使用していると仮定します。

モデル内で、次のようにします。

 accessible_attributes = self.class.inheritable_attributes.delete(:attr_accessible)

また、後で復元することも良い考えです。

 self.class.inheritable_attributes.delete(:attr_accessible) = accessible_attributes

attr_protectedこれは、および と同じように機能します。attr_readonly

そして第二部へ。ユーザータイプごとに、変更できる属性を持つ配列があると思います。

例えば:

 self.class.inheritable_attributes[:attr_accessible] = 
      Set.new(@current_user.allowed_attributes(:post))

また

 self.class.inheritable_attributes[:attr_protected] = 
      Set.new(@current_user.restricted_attributes(:post))

whereallowed_attributesは次のような配列を返します['parent_id', 'published', 'title']

于 2010-07-22T16:36:51.643 に答える