Created
July 24, 2013 14:07
-
-
Save jvidalba1/6070902 to your computer and use it in GitHub Desktop.
Dynamic attributes
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
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) |
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
class Account < ActiveRecord::Base | |
self.table_name = "accounts" | |
attr_accessible :account, :entity_id | |
end |
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
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