SyntaxHighlighter

Saturday, March 22, 2014

Given a string to build a Rails object relationship

In situations where you want to take in a string - like when you are taking the results of an autocomplete, to form a relationship with another object - this is a pattern I like to use...

For example, say you wanted to credit an article to an author. There are many authors in the system, and their names are known. You might want to edit an article and change the name of the author...

In that situation, to build the relationship with the author (and set the foreign key), it takes a little effort to find the author by name, if he's not there, create a new author using the entered name.

attr_accessible :body, :title, :author_name
attr_accessor :body, :title, :author_name

before_validation :set_author
after_initialize :set_author_name

def set_author_name
  self.author_name ||= author.try(:name)
end

def set_author
  self.author = Author.where(:name => author_name).first_or_initialize
end

No comments:

Post a Comment