测试问题中的强参数

时间:2014-05-12 18:54:42

标签: ruby-on-rails ruby strong-parameters

Rails 4.1.1上的Ruby 2.1.1p76。

请查看我的控制器:

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提交一个问题,但最有可能的是我做错了什么并且无法解决问题。

1 个答案:

答案 0 :(得分: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键AND值。因此,那些被传递给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