我在新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
任何想法?
您可以發佈用戶創建表單嗎?具體是下拉。 –
同意JKen13579。我們需要看看這個表格。 –
我已經更新了這個問題,基本上我沒有UI,但正在使用RSpec進行測試。 – Dofs