【问题标题】:Rails ID error with Collection Check Boxes集合复选框的 Rails ID 错误
【发布时间】: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"=&gt;{"city"=&gt;"Denver", "country_id"=&gt;["", "3"]} 并收到此错误 {:action=&gt;"show", :controller=&gt;"locations", :id=&gt;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


    【解决方案1】:

    试试这个:

    locations/new.html.erb

    <%= f.label :country_id %>
    <%= f.check_box :country_id, Country.pluck(:id, :name) %>
    

    locations_controller.rb

    def location_params
       params.require(:location).permit(:city, :country_id)
    end
    

    在视图中的表单中,您使用f. 帮助器告诉参数位于 :location 散列中。只要你写了form_for @location,表单的所有结果都会在 :location hash 内到达服务器。

    在控制器中,您希望 :country_ids 参数中包含数组,但只要您只想发送一个 id,您就必须更改它。

    【讨论】:

    • 我得到的错误是:“数组没有隐式转换成哈希”
    • 尝试复制我的代码。您不应该像您所做的那样将一个标签包含在另一个标签中(根据您的评论)。你根本不需要 :collection_check_boxes 标记
    猜你喜欢
    • 1970-01-01
    • 2012-10-14
    • 2023-03-21
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多