0

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.