Created
April 2, 2009 23:11
-
-
Save moser/89556 to your computer and use it in GitHub Desktop.
AR association accessor with string acceptance
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
# 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