Created
February 11, 2014 05:47
-
-
Save joshnuss/8929855 to your computer and use it in GitHub Desktop.
Set model relationship using key instead of object
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
module AttributeKeyWriter | |
extend ActiveSupport::Concern | |
module ClassMethods | |
protected | |
# Allow writing an attribute by key/code | |
# | |
# Example: | |
# belongs_to :currency | |
# attr_key_writer(:currency, key: "code") | |
# | |
# And now you can set the value with either object or code | |
# user.currency = Currency.find(1) | |
# user.currency = "USD" | |
def attr_key_writer(*attributes) | |
options = attributes.extract_options! | |
key = options[:key] || :code | |
attributes.each do |attribute| | |
define_method("#{attribute}=") do |value| | |
super(value.is_a?(String) ? attribute.to_s.classify.constantize.where(key => value).first : value) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment