samedi 13 novembre 2021

Rails ID error with Collection Check Boxes

I am working on a form to create a location (id, city, country_id) where the user enters the name of the city and then selects a country (id, name) from the following check boxes (collection_check_boxes).

I am using forms_for and passing an object from my LocationsController,

def new
    @location = Location.new
end 

   
#=>locations/new.html.erb
<%= form_for @location do |f| %>
    
    <%= f.label :city %>
    <%= f.text_field :city %>
    
    <br>
    <%= f.label :country %>
    <%= f.collection_check_boxes :location, :country_ids, Country.all, :id, :name %>
    
    <br>
    <%= f.submit 'Create New Location' %>
<% end %>

I get "location"=>{"city"=>"Denver", "country_id"=>["", "3"]} in my params when I submit the form and I get this error {:action=>"show", :controller=>"locations", :id=>nil}, missing required keys: [:id]

The following is my create and secure params methods::

def create
   redirect_to location_path(Location.create(location_params))
end

private

def location_params
   params.require(:location).permit(:city, country_ids: [])
end

I want to be able to only allow one check box for the country because a location shouldn't have more than one country (city: 'Denver, country_id: ['1', '3']) and create a new location with the selected country.




Aucun commentaire:

Enregistrer un commentaire