开发者

Updating object with belongs_to associations and nested_attributes

开发者 https://www.devze.com 2023-04-10 18:58 出处:网络
I\'ve got problems with making update action for 开发者_开发百科one of my data objects. I\'ve got:

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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号