【发布时间】: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