【问题标题】:Rails collection_select not getting an idRails collection_select没有得到一个ID
【发布时间】:2020-11-24 04:56:47
【问题描述】:

我正在尝试进一步了解 Rails 表单控件中的 collection_select 是如何工作的。

物品控制器

class ItemsController < ApplicationController
  def index
    @items = Item.all
  end

  def new
    @item = Item.new
    @categories = Category.all
  end

  def create
    @item = Item.new(params.require(:item).permit(:name, :description, :category))
    render plain: @item.inspect
    # @item.save
    # redirect_to my_page_path
  end

  def show
    @item = Item.find(params[:id])
  end
end

HTML

<div class="form-group">
    <%= f.label :category %>
     <%= f.collection_select(:category_ids, Category.all, :id, :name,
            { prompt: "Make your selection from the list below"}, { multiple: false, size: 1, class: "custom-select shadow rounded" }) %>
  </div>

当我渲染代码时,我得到 category_id = nil

#<Item id: nil, name: "Yo", description: "Brand new", created_at: nil, updated_at: nil, category_id: nil>

谢谢您....任何有关解释的帮助将不胜感激。

【问题讨论】:

  • 您能否添加更多有关该错误的信息?选择下拉列表中是否填充了类别 ID?您从哪里获得类别 id 为 null 的项目?

标签: ruby-on-rails ruby ruby-on-rails-4 ruby-on-rails-5


【解决方案1】:

我在代码中发现了两个问题。您已经注意到对象上的category_idnil

查看collection_select 帮助器设置category_ids 的表单,但您的模型的属性名为category_ids。只需删除复数s

<%= f.collection_select(:category_id, Category.all, :id, :name,
        # ... %>

另一个问题是控制器中StrongParameters 的配置。强大的 params 方法正在处理 params 哈希,并且不知道存在 category 关联并且该关联与 category_id 一起使用。因此,您需要精确并将category_id 添加到列表中:

def create
  @item = Item.new(params.require(:item).permit(:name, :description, :category_id))
  render plain: @item.inspect
  # @item.save
  # redirect_to my_page_path
end

【讨论】:

  • 非常感谢您的时间和解释!
【解决方案2】:
f.collection_select(:category_ids

第一个参数应该是:category_id,因为这是外键属性

【讨论】:

    猜你喜欢
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    • 2014-04-07
    • 2014-09-01
    相关资源
    最近更新 更多