Skip to content

Instantly share code, notes, and snippets.

@jvidalba1
Created July 24, 2013 14:07
Show Gist options
  • Save jvidalba1/6070902 to your computer and use it in GitHub Desktop.
Save jvidalba1/6070902 to your computer and use it in GitHub Desktop.
Dynamic attributes
If you have a method or attribute in a class, you could invoke the send() method in order to call those
methods or attributes.
In my case, I was confused when I was trying to do a validator for my class Transaction which has
another class associated Account, and there is a class called Entity.
I needed validate that an specific account was created in the Account model and belonged to the
same entity.
====
Contribution by [@rderoldan1](https://gist.github.com/rderoldan1)
class Account < ActiveRecord::Base
self.table_name = "accounts"
attr_accessible :account, :entity_id
end
class Transaction < ActiveRecord::Base
# This is the method which goes to the Account model and verifies the entity and the account(attr)
def validation_account_entity(attr)
errors.add(attr, " not configured") unless Account.exists?(:entity_id => self.entity_id, :account => self.send(attr))
end
self.table_name = "transactions"
attr_accessible :account_id, :entity_id
validates :account_id, :presence => true
# send the attribute to validate, you can't forget the colon before it
validate "validation_account_entity(:account_id)"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment