public
Last active

A solution to a more obscure problem related to the "vulnerability" of mass assignment:

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
# account.rb
class Account < ActiveRecord::Base
has_many :users
has_many :services
end
 
# user.rb
class User < ActiveRecord::Base
belongs_to :account
end
 
# services.rb
class Service < ActiveRecord::Base
belongs_to :account
belongs_to :responsible, :class_name => "User"
attr_accessible :responsible_id
validates_account_of :responsible
end
 
# lib/validates_account_of.rb
module ValidatesAccountOf
 
def validates_account_of(*attr_names)
configuration = { :message => "has invalid account", :allow_nil => true, :account_field => :account_id, :self_account_field => :account_id }
configuration.update(attr_names.extract_options!)
 
validates_each(attr_names, configuration) do |record, attr_name, value|
record.errors.add(attr_name.to_sym, configuration[:message]) if value.nil? or value[configuration[:account_field]] != record[configuration[:self_account_field]]
end
 
end
 
end
 
ActiveRecord::Base.extend ValidatesAccountOf

@rafaelp - I think the :message should be can't be blank - from the app user perspective there should be no other accounts and this should be completely transparent.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.