-
-
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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