user3358045
user3358045

Reputation: 7

Foreign key is still nil after relation was built

I have problem while creating new user with address. I create record in Users and Addresses table, but foreign key to address in user is still nil.

class User < ActiveRecord::Base
  belongs_to :address
  accepts_nested_attributes_for :address
end

class Address < ActiveRecord::Base
  has_one :user
end

def new
    @user = User.new
    @user.build_address
  end

  def create
    @user = User.new(user_params)
    if @user.save
      flash[:notice] = "Your account has been created."
      redirect_to signup_url
    else
      flash[:notice] = "There was a problem creating you."
      render :action => :new
    end
  end

private
  def user_params
    params.require(:user).permit(
      :first_name, 
      :last_name, 
      :email, 
      :password, 
      :password_confirmation,
      address_attributes: [:id, :city]
    )
  end
end

Thank you.

Upvotes: 0

Views: 51

Answers (1)

Anri
Anri

Reputation: 6265

You mixed up relation types. Try this:

class User < ActiveRecord::Base
  has_one :address
end

class Address < ActiveRecord::Base
  belongs_to :user
end

Also your code is structured funny, two models and then some methods out of their context. I hope it's just a misprint. If not, put everything except Address model into User model.

Upvotes: 1

Related Questions