Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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

@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

@tomewk +1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.