I've got problems with making update action for 开发者_开发百科one of my data objects. I've got:
class UserProfile < ActiveRecord::Base
belongs_to :address, :dependent => :destroy
belongs_to :post_address, :class_name => 'Address', :dependent => :destroy
accepts_nested_attributes_for :address
accepts_nested_attributes_for :post_address
# validations and stuff
end
class Address < ActiveRecord::Base
# validations and stuff
end
And the problem is with the form and action:
= form_for @up, :url => '/profile/edit', :method => :post do |f|
= f.error_messages
#...
= f.fields_for :address, @up.address do |a|
#...
= f.fields_for :post_address, @up.post_address do |a|
#...
.field.push
= f.submit 'Save', :class=>'ok'
Action:
def edit_account
@user = current_user
if request.post?
@up = @user.user_profile.update_attributes(params[:user_profile])
if @up.save
redirect_to '/profile/data', :notice => 'Zmiana danych przebiegła pomyślnie.'
end
else
@up = @user.user_profile
end
end
The error I get looks like this:
Couldn't find Address with ID=3 for UserProfile with ID=2
And it occurs in the line:
@up = @user.user_profile.update_attributes(params[:user_profile])
I think that AR tries to create another Address
when the form is submitted but I'm not certain.
Why do I get this error? What's wrong with my code?
So not sure how that works on new since @up.address is nil. Can you try something like:
=f.fields_for :address, (@up.address.nil? ? Address.new() : @up.address) do |a|
#...
= f.fields_for :post_address, (@up.post_address.nil? Address.new() : @up.post_address) do |a|
#...
That might make a difference?
Solved
I just changed the type of association in UserProfile
:
has_one :address,
:class_name => 'Address',
:foreign_key => 'user_profile_id',
:conditions => {:is_post => false},
:dependent => :destroy
has_one :post_address,
:class_name => 'Address',
:foreign_key => 'user_profile_id',
:conditions => {:is_post => true},
:dependent => :destroy,
:validate => false
And slightly adjusted the controller. Thanks for help!
精彩评论