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’.
Share
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.
Disclaimer: code has not been verified. Be sure to review, validate, understand, and enhance with error checking.