Ruby on rails 无法保存产品\u id键,是否有\u和\u属于\u多个表?关键是自动递增
我对在has\u和\u-allown\u-to\u-many表中创建新链接感到困惑 我认为我使用的.build(…)是不正确的,但我找不到一种方法来修复它 我写道:Ruby on rails 无法保存产品\u id键,是否有\u和\u属于\u多个表?关键是自动递增,ruby-on-rails,relationship,has-and-belongs-to-many,Ruby On Rails,Relationship,Has And Belongs To Many,我对在has\u和\u-allown\u-to\u-many表中创建新链接感到困惑 我认为我使用的.build(…)是不正确的,但我找不到一种方法来修复它 我写道: @user = User.find(1) if (params[:product_id]) @user.products.build(params[:product_id]) end logger.debug "product id is #{params[:product_id]}" respond_to do |form
@user = User.find(1)
if (params[:product_id])
@user.products.build(params[:product_id])
end
logger.debug "product id is #{params[:product_id]}"
respond_to do |format|
if @user.save
...
我的表products\u users中保存的关系是自动递增的???
我的表的内容示例:(user_id;product_id)={(1;16)(1;17)(1;18)…}
它用这些新id在products表中创建Black线?这是一个建立的原因吗
但是在记录器中,我看到了:params[:product_id]的正确值。。。我忘了什么-
模型是:
class User < ActiveRecord::Base
has_and_belongs_to_many :products
end
class Product < ActiveRecord::Base
belongs_to :group
has_and_belongs_to_many :authors
has_and_belongs_to_many :users
end
class用户
而不是使用
@user.products.build(params[:product_id])
试一试
@user.product\u id这对我来说很有用
@user = User.find(1)
if (params[:product_id])
@product = Product.find(params[:product_id])
unless @user.products.include?(@product)
@user.products << @product
end
end
@user=user.find(1)
if(参数[:产品标识])
@product=product.find(参数[:product\u id])
除非@user.products.include?(@product)
@我确实做了一些类似的事情。以下是对我有效的方法:@user=user.find(1)if(params[:product_id])@product=product.find(params[:product_id]),除非@user.products.include?(@product)@user.products看起来比您需要的代码更多;您不必在此处实例化@product。也许可以试试@user.product\u id之类的东西
@user = User.find(1)
if (params[:product_id])
@product = Product.find(params[:product_id])
unless @user.products.include?(@product)
@user.products << @product
end
end