<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
	<channel>
		<title><![CDATA[Rails Forum - Ruby on Rails Help and Discussion Forum - Custom callback]]></title>
		<link>http://railsforum.com/viewtopic.php?id=51768</link>
		<description><![CDATA[The most recent posts in Custom callback.]]></description>
		<lastBuildDate>Fri, 28 Dec 2012 01:33:41 +0000</lastBuildDate>
		<generator>PunBB</generator>
		<item>
			<title><![CDATA[Custom callback]]></title>
			<link>http://railsforum.com/viewtopic.php?pid=157876#p157876</link>
			<description><![CDATA[<p>I&#039;m building an app that allows users to set their current town and hometown from a huge table (millions of records), so I implemented it without relations (it&#039;s faster than using relations, even with cache). I used some custom code to normalize inputs and discard invalid &#039;city&#039; IDs.</p><p>The thing is, how good is my code? I&#039;m new to Ruby/Rails, and I was wondering if I&#039;m not doing things the hard (or wrong) way.</p><div class="codebox"><pre><code>class UserProfile &lt; ActiveRecord::Base
  attr_accessible :town_current, :town_home, :town_current_id, :town_home_id

  # Callbacks
  before_validation :town_ids_exist

  def town_ids_exist
    validate_town &#039;town_current&#039;, self.town_current_id
    validate_town &#039;town_home&#039;, self.town_home_id
  end

  def validate_town(field, id)
    town = town_exists id

    if town.nil?
      send &quot;#{field}_id=&quot;, nil
      send &quot;#{field}=&quot;, nil
    else
      send &quot;#{field}=&quot;, town.city
    end
  end

  def town_exists(id)
    Location.find_by_id(id)
  end
end</code></pre></div>]]></description>
			<author><![CDATA[dummy@example.com (guhemama)]]></author>
			<pubDate>Fri, 28 Dec 2012 01:33:41 +0000</pubDate>
			<guid>http://railsforum.com/viewtopic.php?pid=157876#p157876</guid>
		</item>
	</channel>
</rss>
