【发布时间】:2016-03-26 05:33:36
【问题描述】:
我有三个模型:ProductType、ProductAttribute 和 ProductTypeAttribute。 ProductType 和 ProductAttribute 是对象,ProductTypeAttribute 是一个连接(使用 has_many :through)。
当用户创建或更新ProductType时,他可以通过复选框选择ProductType中的ProductAttributes。
我的问题:
- 在连接表 (ProductTypeAttribute) 中只创建了一条记录,没有参考选中了多少个复选框
- 在连接表中只有“product_type_id”有值,“product_attribute_id”为NULL
感谢您的帮助!
我的 ProductType 模型:
class ProductType < ActiveRecord::Base
has_many :product_type_attributes, dependent: :destroy
has_many :product_attributes, through: :product_type_attributes
end
我的 ProductAttribute 模型:
class ProductAttribute < ActiveRecord::Base
has_many :product_type_attributes, dependent: :destroy
has_many :product_types, through: :product_type_attributes
end
我的 ProductTypeAttribute 模型:
class ProductTypeAttribute < ActiveRecord::Base
belongs_to :product_type
belongs_to :product_attribute
end
我的表格:
<%= form_for @product_type do |f| %>
<% if @product_type.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(@product_type.errors.count, "error") %> prohibited
this product type from being saved:
</h2>
<ul>
<% @product_type.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label "product type name" %><br>
<%= f.text_field :type_name %>
</p>
<p>
<%= f.label "description" %><br>
<%= f.text_area :type_desc %>
</p>
<% ProductAttribute.all.each do |attribute| %>
<label>
<%= check_box_tag 'attribute_ids[]', attribute.id, @product_type.product_attributes.include?(attribute) %>
<%= label_tag :attribute_ids, attribute.name %>
</label>
<% end %>
<p>
<%= f.submit %>
</p>
<% end %>
我的产品类型控制器
class ProductTypesController < ApplicationController
def index
@product_types = ProductType.all
end
def show
@product_type = ProductType.find(params[:id])
end
def new
@product_type = ProductType.new
end
def edit
@product_type = ProductType.find(params[:id])
end
def create
@product_type = ProductType.new(product_type_params)
@product_type.product_type_attributes.build
@product_type.save
redirect_to @product_type
end
def update
@product_type = ProductType.find(params[:id])
@product_type.product_type_attributes.build
if @product_type.update(product_type_params)
redirect_to @product_type
else
render 'edit'
end
end
def destroy
@product_type = ProductType.find(params[:id])
@product_type.destroy
redirect_to product_types_path
end
def product_type_params
params.require(:product_type).permit(:type_desc, :type_name, {attribute_ids: []})
end
end
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4