Skip to content

Instantly share code, notes, and snippets.

@joshnuss
Created February 11, 2014 05:47
Show Gist options
  • Save joshnuss/8929855 to your computer and use it in GitHub Desktop.
Save joshnuss/8929855 to your computer and use it in GitHub Desktop.
Set model relationship using key instead of object
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