I have a model that contains a country_id and region_id. The form posts back the name of the country and region (as params[:country] and params[:region]) instead of the ids. This creates a problem when calling 'new'. Is it possible to add code to the model so that the countries and regions can be located by name? I am currently doing it in the controller, but want the code to be more reusable. Is it generally acceptable to override 'new'? This will also be called on 'update'.
+1
A:
You can add accessors in the model for country and region, which can do the lookup and set the appropriate database parameter. So in this example, "country" becomes a settable virtual attribute.
class Location
attr_accessor :country
def country= value
country = Country.find_by_name value
self.country_id = country.id if country.present?
end
end
Disclaimer: code has not been verified. Be sure to review, validate, understand, and enhance with error checking.
fullware
2010-06-26 00:08:29
Thanks for the response. Just one question, the code already uses a 'has_one :country' and 'has_one :region'. Will this cause issues? I like being able to assign the country using '@model.country = Country.find...' elsewhere in the code. Thanks again.
Kevin Sylvestre
2010-06-26 00:20:50
Probably best to test it out -- @model.country= should work just fine, what's missing from my example is the reader (def country without the = ) to return it. In that case, you wouldn't need the has_one declaration at all. Might have to experiment a bit there, good luck.
fullware
2010-06-28 16:53:18