我有一个链接表关联的两个模型没有id字段,而是一个复合键[product_id,product_set_id]。
我对它们进行了唯一性验证。
我正在尝试设置一个嵌套表单,但是我注意到了以下问题:更新时,似乎activerecord正在尝试创建一个新条目,因此它失败了。
例如,这是一个发送到补丁的示例参数哈希:
Parameters: {"product_set"=>{"name"=>"Marea", "created_by_id"=>"1", "product_product_sets_attributes"=>{"0"=>{"product_id"=>"420", "product_set_id"=>"4", "_destroy"=>"1"}, "1"=>{"product_id"=>"423", "product_set_id"=>"4", "_destroy"=>"0"}}}, "commit"=>"Atualizar", "id"=>"4"}
我已经读过某个地方,当没有:参数中的id时AR假设它必须创建一个新记录......但是我怎么能告诉它不要尝试创建一个新记录?
validates :product_set_id, uniqueness: { scope: :product_id, message: "This product is already part of this set." }
编辑:
型号:
class ProductProductSet < ActiveRecord::Base
belongs_to :product
belongs_to :product_set
validates :product_set_id, uniqueness: { scope: :product_id, message: "This product is already part of this set." }
end
class ProductSet < ActiveRecord::Base
belongs_to :created_by, class_name: 'User', foreign_key: 'created_by_id'
has_many :product_product_sets, dependent: :destroy
has_and_belongs_to_many :products, :join_table => :product_product_sets
# has_many :products, through: :product_product_sets, source: :product
accepts_nested_attributes_for :product_product_sets, :allow_destroy => true
end
product_sets_controller.rb
def product_set_params
params.require(:product_set).permit(:name, :created_by_id, product_product_sets_attributes: [:product_id, :product_set_id, '_destroy'])
end
查看(当然没有完成):
= simple_form_for(@product_set) do |f|
- if @product_set.errors.any?
.alert.alert-danger
%ul
- @product_set.errors.full_messages.each do |msg|
%li= msg
.form-inputs
.form-group
= f.input :name, class: 'form-control'
= f.association :created_by, class: 'form-control'
/ = text_field_tag 'product_set[product_ids][]', nil, { multiple: true, class: "form-control" }
/ = link_to 'add', 'javascript:void(0);', id: "add_link"
.existing-products
= f.fields_for( :product_product_sets, include_id: false ) do |builder|
= image_tag builder.object.product.image.url(:thumb)
= builder.hidden_field :product_id
= builder.hidden_field :product_set_id
= builder.check_box :_destroy
= builder.label :_destroy, "Remove Product"
答案 0 :(得分:1)
在你的update action / params hash中,我认为你需要将集合对象id作为数组传递。这样的事可能呢?
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String str = input.nextLine();
doubleStr(str);
}
public static void doubleStr(String s)
{
char[] array = s.toCharArray();
for(char a: array)
{
if(a>='0' && a<='9')
{
System.out.print(a);
}else if(a=='!')
{
for(int i=0; i<=2; i++)
{
System.out.print(a);
}
}
else
{
for(int i=0; i<=1; i++)
{
System.out.print(a);
}
}
}
}
我的理解是有限的,但我认为由于Rails默认情况下不支持复合键,你肯定需要 "product_product_sets_attributes"=> {
"id" => [product.id, product_set.id]
}
,然后在模型中需要以下语法风格???
composite keys gem
如果不是这样的话,有兴趣了解更多。