2014-06-13 25 views
1

我在新Rails 4應用程序中允許使用外鍵問題。如何使用強大的外鍵參數

假設您有一個用戶創建表單,您可以在其中創建一個用戶並通過下拉菜單分配用戶類型。

用戶模型將有一個外鍵:user_type_id

我有一個使用FactoryGirl一個RSpec的測試,如果我調試,並期待在PARAMS的user_type的值爲2,但如果我的許可證PARAMS是這樣的:

private 

def user_params 
    params.require(:user).permit(:name, :password, :user_type_id) 
end 

我不會得到任何user_type輸出。我也試過:

private 

def user_params 
    params.require(:user).permit(:name, :password, user_type_attributes: [:user_type_id]) 
end 

但沒有任何運氣。

在我的用戶控制器中,在我的發佈操作中允許它的方式是什麼?

更新:

我沒有UI呢,我試着這樣做TDD方式,所以基本上這是我的RSpec的測試,其失敗。

創建用戶操作是這樣的:

def create 
    @user = User.new(user_params) 
    authorize @user 

    respond_to do |format| 
     if @user.save 
      format.html { render json: @user, status: :created, location: @user } 
      format.json { render json: @user, status: :created, location: @user } 
     else 
      format.html { render json: @user, status: :unprocessable_entity, location: @user } 
      format.json { render json: @user.errors, status: :unprocessable_entity } 
     end 
    end 
end 

和RSpec的測試是這樣的:

it 'should create a user' do 
       expect { 
        post :create, { :user => FactoryGirl.attributes_for(:User) } 
       }.to change(User, :count).by(1) 
      end 

的FactoryGirl爲我的用戶是這樣的:

FactoryGirl.define do 
    factory :User do |f| 
     f.email { Faker::Internet.email } 
     f.password { '12345678' } 
     f.password_confirmation { '12345678' } 
     f.user_type { FactoryGirl.create(:UserType) } 
    end 
end 

如果我調試了我的@user對象,它沒有添加user_type,但是如果我d ebug params對象,它包含一個user_type: 2

任何想法?

+1

您可以發佈用戶創建表單嗎?具體是下拉。 –

+0

同意JKen13579。我們需要看看這個表格。 –

+0

我已經更新了這個問題,基本上我沒有UI,但正在使用RSpec進行測試。 – Dofs

回答

1

您並未在工廠中創建Id。您正在創建新的關聯對象。您必須在傳遞給控制器​​的參數中檢索ID。

我建議:

FactoryGirl.define do 
    factory :User do |f| 
     f.email { Faker::Internet.email } 
     f.password { '12345678' } 
     f.password_confirmation { '12345678' } 
     f.user_type 999 
    end 
end 

在您的規格:

before(:each) do 
    type = FactoryGirl.create(:UserType, id: 999) 
end 

然後:

it 'should create a user' do 
    expect { :create, { :user => FactoryGirl.attributes_for(:User)} 
        }.to change(User, :count).by(1) 
end 

並從FactoryGirl行動的關聯。

編輯: 如果用戶類型是強制性的,並且假設您在數據庫中包含它們,則只需在工廠中插入用戶類型所需的user_id即可。之後你不需要合併參數。

+0

好吧,我真的以爲:f.user_type {FactoryGirl.create(:UserType)}將分配user_type_id與創建的用戶類型... – Dofs

+0

不,它在該字段內創建一個新對象。我的解決方案有效嗎? – tebayoso

+0

好的,如果你可以在現場創建一個對象,並且同時將它分配給FactoryGirl,那會很酷。使用合併屬性似乎不太乾燥。 – Dofs