Skip to content

Instantly share code, notes, and snippets.

@rafaelp
Created March 5, 2012 04:55
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rafaelp/1976687 to your computer and use it in GitHub Desktop.
Save rafaelp/1976687 to your computer and use it in GitHub Desktop.
A solution to a more obscure problem related to the "vulnerability" of mass assignment:
# 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
@tomekw
Copy link

tomekw commented Mar 5, 2012

@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.

@mergulhao
Copy link

@tomewk +1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment