【发布时间】:2018-10-19 17:29:35
【问题描述】:
如果选择了多个,我希望将多个(一组...)category_id 保存到每个列表中。以下是所有内容的设置方式,包括类别如何与列表一起使用。
类别型号:
class Category < ApplicationRecord
validates_uniqueness_of :category
has_many :listings
上市模式:
has_and_belongs_to_many :categories, required: false
attr_accessor :new_category_name
before_save :create_category_from_name
# has_many :categories
方案(用于类别和列表):
create_table "categories", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "listings", force: :cascade do |t|
t.string "name"
t.text "description"
t.decimal "price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "image"
t.integer "user_id"
t.integer "category_id"
t.index ["category_id"], name: "index_listings_on_category_id"
end
然后我在 seed.rb 中定义了类别,然后在我需要添加它们时使用 rails db:seed 输入它们。
新的列表控制器:
def new
@listing = Listing.new
@categories = Category.all
3.times do
@listing.categories.build
end
end
用于创建列表的表单视图(简要):
<%= form_with(model: listing, local: true) do |form| %>
<%= form.label "Choose Up to 3 Categories (1 required)"%>
<div class="space">
<%= form.select :category_id, options_from_collection_for_select(Category.all, :id, :name), :prompt => "Select a Category" %>
<%= form.select :category_id, options_from_collection_for_select(Category.all, :id, :name), :prompt => "Select a Category" %>
<%= form.select :category_id, options_from_collection_for_select(Category.all, :id, :name), :prompt => "Select a Category" %>
</div>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<%= form.label "Choose Up to 3 Categories (1 required)"%>
<div class="space">
<% form.fields_for :category_id do |c| %>
<%= c.select :category_id, options_from_collection_for_select(Category.all, :id, :name), :prompt => "Select a Category" %>
<% end %>
</div>
<% form.fields_for :category_id do |c| %>
<%= c.text_field :category_id %>
<% end %>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
在“~~~~~~~~~~~~~~~~~~~~~”之间是我测试它的尝试。但它们甚至没有出现在表单中,我不知道为什么。
当我使用第一个“form.select :category_id”时,它会显示 3 个下拉菜单,只有最后选择的下拉菜单会保存。如果我选择 3 个单独的类别,则只有最后一个选择会保存。我希望能够为每个列表选择多个类别。
创建新列表时如何允许保存多个类别?无论是下拉菜单、复选框等。如果用户选择了多个列表,则只需将多个选项保存到一个列表中即可。
更新:
架构:
create_table "categories", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "categories_listings", id: false, force: :cascade do |t|
t.integer "category_id", null: false
t.integer "listing_id", null: false
end
查看表格:
<%= form.select :category_ids, options_from_collection_for_select(Category.all, :id, :name), :prompt => "Select a Category", :multiple => true %>
控制参数:
params.require(:listing).permit(:attr1, :name, :description, :price, :image, :category_id, category_ids: [])
型号:
Category
has_and_belongs_to_many :listings
Listing
belongs_to :category, required: false
belongs_to :categories_listings, required: false
【问题讨论】:
-
thx 将其修复为仅相关
标签: ruby-on-rails ruby ruby-on-rails-4