Skip to content

Instantly share code, notes, and snippets.

@bobanj
Forked from rafaelp/gist:1976687
Created March 5, 2012 11:37
Show Gist options
  • Save bobanj/1977960 to your computer and use it in GitHub Desktop.
Save bobanj/1977960 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment