kevin lopez
kevin lopez

Reputation: 87

Params not being read in controller action

I am setting up a state picker drop down the end goal is for the user to choose a state and the select tag below to populate with cities for that state im using the city-state gem https://github.com/loureirorg/city-state

I have gotten the correct parameters in my request but they are not being read by the controller method.

registrations-controller.rb

def new
  super
  @cities = CS.get(:us,params[:state]) 
  puts @cities                 
end

this is not picking up the :state param

new.html.erb

 <%= select_tag :state,options_for_select(CS.states(:us)), 
  {:class => "signup-input-container--input", :id => "state-picker"} %>

routes.rb

devise_scope :family do
  get 'states', to: 'families/registrations#new'
end

main.js

  var state = document.getElementById("state-picker");
  state.addEventListener("change", function() {
     $.ajax({
        url: "/states?state=" + state.value,
        type: "GET"
     })
  })

Anyone know why this is happening? I also logged the params and got.

 "<ActionController::Parameters {"state"=>"Colorado", "controller"=>"families/registrations", "action"=>"new"} permitted: false> " 

Upvotes: 2

Views: 1067

Answers (2)

Paulo Belo
Paulo Belo

Reputation: 4457

If you get permitted: false in ActionController::Parameters it's probably because you are not whitelisting your parameters (:state in this case) in your controller, like required by Strong Parameters

From the docs:

With strong parameters, Action Controller parameters are forbidden to be used in Active Model mass assignments until they have been whitelisted.

Example:

private
  def person_params
    params.require(:person).permit(:name, :age)
  end

Upvotes: 0

David
David

Reputation: 1970

The docs suggest that the cities method wants a symbol for the state. You're using the simplified get method but it probably also wants a symbol instead of the name of the city as a String (which is what we can see in your params).

So maybe main.js should have the following:

 $.ajax({
    url: "/states?state=" + state.key, // 'state.value' was the string of the state name, we want the two-letter code.
    type: "GET"
 })

You'll probably also have to change this line

@cities = CS.get(:us,params[:state]) 

to this

@cities = CS.get(:us,params[:state].to_s) 

Upvotes: 1

Related Questions