[英]How to add multiple categories in Rails?
我在 Rails 5.2.3 和 Mongoid 上使用 Ruby
我尝试添加多个类别。
类别.rb
class Category
include Mongoid::Document
has_many :tickets
belongs_to :user
end
票证.rb
class Ticket
include Mongoid::Document
belongs_to :user
belongs_to :category, touch: true
end
门票/_form.html.erb
<%= form_for(@ticket, html: { role: 'form' }) do |f| %>
<%= f.collection_select :category_id, Category.all, :id, :title, options = { include_hidden: false }, html_options = { multiple: true } %>
<%= f.submit 'Save' %>
<% end %>
当我尝试保存时出现“类别不能为空白”的错误
日志
Processing by TicketsController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"rZyRkTPqTdM//ymnKGsm4Ctm5Co7YgAnSQg6oOaOVv4qEua1QB6cxclId2H4lm1rHG49H/2KomLWab1FaKnf1g==", "ticket"=>{"name"=>"test", "description"=>"test", "category_id"=>["5d0939d51996da62c1bd4699", "5d0939de1996da62c1bd469a"]}, "commit"=>"Save"} MONGODB | 本地主机:27017 | remote_development.find | 开始 | {"find"=>"users", "filter"=>{"_id"=>BSON::ObjectId('5d77b34d1996da1a261c111d')}, "sort"=>{"_id"=>1}, "limit"= >1, "singleBatch"=>true, "lsid"=>{"id"=>}} MONGODB | 本地主机:27017 | remote_development.find | 成功 | 0.002s MONGODB | 本地主机:27017 | remote_development.find | 开始 | {"find"=>"categories", "filter"=>{"_id"=>[BSON::ObjectId('5d0939d51996da62c1bd4699'), BSON::ObjectId('5d0939de1996da62c1bd469a')]}, "limit"=>1 , "singleBatch"=>true, "lsid"=>{"id"=>}} MONGODB | 本地主机:27017 | remote_development.find | 成功 | 0.003s 渲染票证/new.html.erb 在布局/应用程序中渲染共享/_error_messages.html.erb (0.9ms) Z941B4882303C4EC4BZB |2DA0666392 本地主机:27017 | remote_development.find | 开始 | {"find"=>"categories", "filter"=>{}, "lsid"=>{"id"=>}} MONGODB | 本地主机:27017 | remote_development.find | 成功 | 0.001s Rendered tickets/_form.html.erb (9.7ms) Rendered tickets/new.html.erb within layouts/application (12.9ms) Rendered shared/_nav.html.erb (1.9ms) Completed 200 OK in 120ms (Views: 104.9ms | MongoDB: 0.0ms)
您将 2 个 ID 传递给名为category_id
的belongs_to
关联。 你实际上需要一个has_many
或has_and_belongs_to_many
关系https://docs.mongodb.com/mongoid/current/tutorials/mongoid-relations/#has-and-belongs-to-many category_ids
它的属性将是一个多关系复数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.