Initializing active record model using invalid parameters
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'.
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.
精彩评论