rails:关联tabel(has_and_belongs_to_many)不保存任何记录
问题描述:
我使用rails 5,简单的形式。在我的应用程序中有一个类别模型,并有一个OnlineProduct模型。我不知道为什么当我想添加一些类别到我的OnlineProduct关联表保持为空并且不要更改。rails:关联tabel(has_and_belongs_to_many)不保存任何记录
分类模型:
class Category < ApplicationRecord
has_ancestry
has_and_belongs_to_many :internet_products
end
InternetProduct模型:
class InternetProduct < ApplicationRecord
belongs_to :user
belongs_to :business
has_and_belongs_to_many :categories
end
InternetProduct控制器:
def new
@internet_product = InternetProduct.new
end
def create
@internet_product = InternetProduct.new(internet_product_params)
respond_to do |format|
if @internet_product.save
format.html { redirect_to @internet_product, notice: 'Internet product was successfully created.' }
format.json { render :show, status: :created, location: @internet_product }
else
format.html { render :new }
format.json { render json: @internet_product.errors, status: :unprocessable_entity }
end
end
end
private:
def internet_product_params
params.require(:internet_product).permit(:name, :description, :mainpic, :terms_of_use,
:real_price, :price_discount, :percent_discount,
:start_date, :expire_date, :couponـlimitation, :slung,
:title, :meta_data, :meta_keyword, :enability, :status,
:like, :free_delivery, :garanty, :waranty, :money_back,
:user_id, :business_id,
categoriesـattributes: [:id, :title])
end
并在视图仅部分谁涉及类:
<%= f.association :categories %>
所有类别列表在视图(窗体),但是当我选择其中一些不保存在数据库中。在滑轨控制台我这样做
p = InternetProduct.find(5)
p.categories = Category.find(1,2,3)
这个保存到数据库没有任何问题,我该怎么办? 坦克阅读本
答
我找到解决方案来解决这个问题。当我们使用has_and_belong_to_many或者有其他关系,如果你想使用集合选择simple_form,在模型中也应该是嵌套形式相关的方法,在新添加此命令
accepts_nested_attributes_for :categories
也在控制器例如我们应该
def new
@internet_product = InternetProduct.new
@internet_product.categories.build
end
你有'OnlineProduct'连接表吗? – inye
是的。这是我的: 'class CategoriesInterBons
Armanlearn
编辑你的问题,并添加这种迁移,如果你添加此三个表的表模式更好。 – inye