Question

Ruby 2.1.1p76 on Rails 4.1.1.

Please check out my controller:

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,
 )

end

See the commented line? In the form above - user_settings_params will not return :district_ids array of ids, and this is fine, since I can use the line below instead to have them (got it from guides).

The problem I have is when running this test:

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

It passes. When debugging user_settings_param has :district_ids available as if strong parameters were disabled or something. I wanted to submit an issue to rails but most probably I'm doing something wrong and can't figure it out.

Was it helpful?

Solution

I've found it - it was because of quirky way I was creating checkboxes for 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

For no particular reason I've inserted ids into params keys AND values. And because of that those were passed to params object as hash. In test though those were sent as array. So it was the view to blame.

= check_box_tag "user_setting[district_ids][]", district.id, user.settings.district_ids.include?(district.id)
= label_tag "user_setting[district_ids][]",  district.name
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top