2014-05-12 67 views
0

Ruby 2.1.1p76 on Rails 4.1.1。測試中的強參數

請看看我的控制器:

def update 
begin 
    current_user.update_settings user_settings_params unless params[:user_setting].blank? 
    current_user.update_attribute :district_id, params[:user][:district_id] unless params[:user].blank? || params[:user][:district_id].blank? 
    flash[:success] = "Preferencje zostały zaktualizowane" 
    redirect_to subscription_index_path 
rescue UserLevelException => exception 
    flash[:alert] = "Sprytnie, za karę zostałeś wylogowany ;)" 
    session[:user_id] = nil 
    redirect_to root_path 
    return 
end 
end 

private 

def user_settings_params 
params.require(:user_setting).permit(
    :inquiry_subject, :inquiry_body, 
    :offer_subject, :offer_body, 
    :only_companies_with_email, 
    {:district_ids => []}, 
    # {:district_ids => params[:user_setting][:district_ids].try(:keys)}, 
    :delivery_address, 
) 

見註釋行?在上面的表格中 - user_settings_params不會返回:district_ids id數組,因爲我可以使用下面的代碼來獲得它們(從指南中獲得它),所以這很好。

這個問題我已經在運行此測試時:

test 'should set user level10 districts' do 
    user = login_user :paid10 

    post :update, :user_setting => {:district_ids => [districts(:zachodniopomorskie).id, districts(:slaskie).id]} 

    assert_equal nil, flash[:alert] 
    assert_equal 'Preferencje zostały zaktualizowane', flash[:success] 


    db_user_districts = User.find(user.id).settings.districts.all 
    assert db_user_districts.include? districts(:zachodniopomorskie) 
    assert db_user_districts.include? districts(:slaskie) 
    assert_equal 2, db_user_districts.count 

end 

它傳遞。在調試user_settings_param時:如果強制參數被禁用或可執行,則可以使用district_ids。我想向rails提交一個問題,但最可能的是我做錯了一些事情,並且無法弄清楚。

回答

0

,我找到了 - 那是因爲古怪的辦法,我創建複選框HABTM

= check_box_tag "user_setting[district_ids][#{district.id}]", district.id, user.settings.district_ids.include?(district.id) 
= label_tag "user_setting[district_ids][#{district.id}]", district.name 

對於我插入ID添加到PARAMS鍵和值沒有特別的理由。因爲那些被傳遞給params對象作爲散列。在測試中,儘管這些是作爲數組發送的。所以這是責怪的觀點。

= check_box_tag "user_setting[district_ids][]", district.id, user.settings.district_ids.include?(district.id) 
= label_tag "user_setting[district_ids][]", district.name