1

I am looking for a way to easily apply attr_accessible to all fields in a model for a given role, so that I can mass assign all fields in my admin console. I'd like to do something like this:

    class User < ActiveRecord::Base
         attr_accessible :name
         attr_accessible :all, :as => :admin
    end

Using :all obviously doesn't work. Is there an easy way I can apply attr_accessible to all fields without having to list them all out, as I have a lot of them, and I don't want to have to remember to do this every time I add a field.

k_day
  • 1,309
  • 2
  • 14
  • 19

3 Answers3

2
attr_accessible *column_names, :as => :admin
René Höhle
  • 24,401
  • 22
  • 66
  • 73
Adam Klein
  • 381
  • 2
  • 10
1

I would implore you to actually take the time to add each field as this offers an opportunity for you to think about whether it actually needs to be attr_accessible. That said, this can be accomplished:

columns.each do |column|
  attr_accessible column.name.to_sym, :as => :admin
end
Josh Rieken
  • 2,196
  • 1
  • 18
  • 22
  • 1
    Probably want `attr_accessible column.name.to_sym, :as => :admin` – Jim Deville Jan 21 '13 at 04:01
  • This works, thanks Josh. I want to be able to manually edit any field in my admin panel, which is why I just want to add them all. I am very cautious about which fields I add to attr_accessible under the default role. Just to clarify, doing what I am doing won't cause a security risk, right? There is no way for a non admin user to specify the role they are mass assigning as, correct? – k_day Jan 21 '13 at 04:54
  • As far as I know, this is secure. – Josh Rieken Jan 21 '13 at 16:52
0

I was wondering to have column_names instead of column :

(column_names - ['col1', 'col2', 'col3']).each do |column|
  attr_accessible column.to_sym
end
Moin Haidar
  • 1,564
  • 1
  • 15
  • 15