2014-02-27 52 views
0

我在創建地址的新用戶時遇到問題。我在「用戶和地址」表中創建記錄,但在用戶中尋址的外鍵仍然爲零。建立關係後外鍵仍然爲零

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 

謝謝。

回答

1

您混淆了關係類型。 試試這個:

class User < ActiveRecord::Base 
    has_one :address 
end 

class Address < ActiveRecord::Base 
    belongs_to :user 
end 

而且你的代碼的結構很有趣,兩個模型,然後一些方法了他們的上下文。我希望這只是一個印刷錯誤。如果沒有,則將除Address模型以外的所有東西都放入User模型中。

+0

我想#new,#create和#user_params是UsersController的動作 –