Using Rails 2.3.8
Goal is to create a Blogger while simultaneously updating the nested User model (in case info has changed, etc.), OR create a brand new user if it doesn't exist yet.
Model:
class Blogger < ActiveRecord::Base
belongs_to :user
accepts_nested_attributes_for :user
end
Blogger controller:
def new
@blogger = Blogger.new
if user = self.get_user_from_session
@blogger.user = user
else
@blogger.build_user
end
# get_user_from_session returns existing user
# saved in session (if there is one)
end
def create
@blogger = Blogger.new(params[:blogger])
# ...
end
Form:
<% form_for(@blogger) do |blogger_form| %>
<% blogger_form.fields_for :user do |user_form| %>
<%= user_form.label :first_name %>
<%= user_form.text_field :first_name %>
# ... other fields for user
<% end %>
# ... other fields for blogger
<% end %>
Works fine when I'm creating a new user via the nested model, but fails if the nested user already exists and has and ID (in which case I'd like it to simply update that user).
Error:
Couldn't find User with ID=7 for Blogger with ID=
This SO question deals with a similar issue, and only answer suggests that Rails simply won't work that way. The answer suggests simply passing the ID of the existing item rather than showing the form for it -- which works fine, except I'd like to allow edits to the User attributes if there are any.
Deeply nested Rails forms using belong_to not working?
Suggestions? This doesn't seem like a particularly uncommon situation, and seems there must be a solution.