【发布时间】:2021-12-25 18:06:49
【问题描述】:
我正在创建一个表单来创建一个位置(id、city、country_id),用户可以在其中输入城市名称,然后从以下复选框(collection_check_boxes)中选择一个国家(id、name)。
我正在使用 forms_for 并从我的 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 %>
当我提交表单时,我在参数中收到 "location"=>{"city"=>"Denver", "country_id"=>["", "3"]} 并收到此错误 {:action=>"show", :controller=>"locations", :id=>nil}, missing required keys: [:id]
以下是我的创建和安全参数方法::
def create
redirect_to location_path(Location.create(location_params))
end
private
def location_params
params.require(:location).permit(:city, country_ids: [])
end
我希望能够仅在国家/地区允许一个复选框,因为一个位置不应包含多个国家/地区 (city: 'Denver, country_id: ['1', '3']),并使用所选国家/地区创建一个新位置。
【问题讨论】:
标签: ruby-on-rails ruby forms checkbox