Skip to content

Instantly share code, notes, and snippets.

@noelrappin
Created July 15, 2011 21:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noelrappin/1085557 to your computer and use it in GitHub Desktop.
Save noelrappin/1085557 to your computer and use it in GitHub Desktop.
module AcceptsDelimtedIdStringFor
# accepts_delimited_id_string_for :careers
#
# becomes
#
# def career_id_strings=(delimited_string)
# self.careers = Career.where(:id => delimited_string.split(",")).all
# end
#
# So...
# object.career_id_strings = ("1,2,3,4")
def accepts_delimited_id_string_for(*associations)
associations.each do |association|
singular = association.to_s.singularize
klass = singular.classify.constantize
define_method :"#{singular}_id_strings=" do |delimited_string|
send(:"#{association}=", klass.where(:id => delimited_string.split(",")).all)
end
end
end
end
ActiveRecord::Base.extend(AcceptsDelimtedIdStringFor)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment