Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moser/89556 to your computer and use it in GitHub Desktop.
Save moser/89556 to your computer and use it in GitHub Desktop.
AR association accessor with string acceptance
# Host is a simple two row model: id, name
# I think the check whether a host with the given
# name exists, should go right there.
# Still it accepts normal host objects.
# A big advantage over Host.find_or_create is,
# that I can use "host" as a normal text field in
# my forms and it's all done automatically.
class MyModel < ActiveRecord::Base
belongs_to :host
def host_with_string_acceptance=(obj)
if obj.is_a?(String)
obj = Host.find_by_name(obj) || Host.create({:name => obj})
end
self.host_without_string_acceptance = obj
end
alias_method_chain :host=, :string_acceptance
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment