我很难过。我收到错误unknown attribute 'products_part' for Part.
我开始尝试通过part
表格创建与许多不同products
相关联的新products_parts
。相关代码:
# schema.rb
create_table "products_parts", force: :cascade do |t|
t.integer "product_id"
t.integer "part_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
如果相关,我现有设置的product_id
表格中存在parts
列,每个产品只允许一个部分。我不认为这会干扰吗?
# part.rb
class Part < ApplicationRecord
has_many :products_parts
has_many :products, through: :products_parts
accepts_nested_attributes_for :products_parts, :allow_destroy => true
end
# products_part.rb
class ProductsPart < ApplicationRecord
belongs_to :product
belongs_to :part
end
# product.rb
class Product < ApplicationRecord
has_many :products_parts
has_many :parts, through: :products_parts
accepts_nested_attributes_for :parts, :allow_destroy => true
end
-
# parts_controller.html.erb
class PartsController < ApplicationController
before_action :set_part, only: [:show, :edit, :update, :destroy]
def new
@part = Part.new
@part.uploads.build
@products_parts = @part.products_parts.build
@product = Product.order(brand_name: :asc).order(manufacturer_model_number: :asc)
end
def create
@part = Part.new(part_params)
if @part.save
redirect_to part_path(@part), notice: '// Part was successfully created.'
else
render :new
end
end
private
def part_params
params.require(:part).permit!
end
end
在submit上传递的参数:
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"f+ObKsfs2QNP6l1MEDGSj6EZERMpHT/7vVKjAumC1aQmeTKdlPJNeSv2IZwNgsVPnKt2Siqi9x5oMmD2Ti8kMQ==",
"part"=>
{"products_part"=>{"product_ids"=>["", "191", "7"]},
"manufacturer_model_number"=>"Screws-HB",
"notes"=>""},
"commit"=>"Create Part"}
-
# _form.html.erb
<%= bootstrap_form_for @part, url: parts_path, method: :post, :html => { :multipart => true } do |f| %>
<%= f.fields_for(@products_parts) do |ff| %>
<%= ff.collection_select(:product_ids, @product, :id, :product_select_with_model,
{:placeholder => "Select Product...", hide_label: true, :selected => @part.products.map(&:id)},
{:multiple => true, :class => 'newPartProductSearch', :style => "width:100%;"}) %>
<% end %>
<%= f.submit "Create Part", :style => "float:right;" %>
<% end %>
我基于this post.的帮助,在此基础上做了很多工作 如果有人对我可以开始解决这个问题的方向有任何想法,我们将不胜感激!
答案 0 :(得分:1)
使用以下代码替换_form
:
# _form.html.erb
<%= bootstrap_form_for @part, url: parts_path, method: :post, :html => { :multipart => true } do |f| %>
<%= f.collection_select(:product_ids, Product.all, :id, :name,
{include_blank: false, :include_hidden => false, :selected => @part.products.map(&:id)},
{:multiple => true}) %>
<%= f.submit "Create Part", :style => "float:right;" %>
<% end %>
未经测试。但希望它能够奏效。