I have a user who has a location that location contains a country_id.
Location has a polymorphic interface locatable.
What works:
The user can edit their name, country and city. This all saves to the DB
on the update put.
The problem:
Returning to the edit page shows the textfield’s name and city populated
but the country select form element defaults to blank. The value for
user.location.country_id is saved in the DB but the form element refuses
to show this as “selected”. I have attempted explicityly setting the
selected :option but still, it fails to show country.
MODEL
user
has_one :location, :as => :locatable, :dependent => :destroy
location
belongs_to :country
belongs_to :locatable, :polymorphic => true
country
has_many :locations
VIEW
<% form_for @user, :html => { :multipart => true } do |form| %>
<% fields_for “user[location_attributes]”,@user.location do
|location_fields| %>
<%= form.submit ‘Update’ %>
<% end %>
CONTROLLER
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
@user.attributes = params[:user]
@user.save!
flash[:notice] = “Your profile has been updated.”
redirect_to url_after_update
rescue ActiveRecord::RecordInvalid
render :action => “edit”
end