[英]rails : association tabel (has_and_belongs_to_many) not save any record
i use rails 5 , simple form. 我使用rails 5,简单的形式。 in my app there is a Category model and there is a OnlineProduct model.
在我的应用程序中,有一个类别模型和一个OnlineProduct模型。 i dont know why when i want to add some categories to my OnlineProduct association table remain empty and don't change.
我不知道为什么要在我的OnlineProduct关联表中添加一些类别时保持空白且不更改。
Category model: 类别模型:
class Category < ApplicationRecord
has_ancestry
has_and_belongs_to_many :internet_products
end
InternetProduct model: 互联网产品型号:
class InternetProduct < ApplicationRecord
belongs_to :user
belongs_to :business
has_and_belongs_to_many :categories
end
InternetProduct controller: 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
and in the view only the part of who relate to categories : 并且认为只有一部分与类别相关的人:
<%= f.association :categories %>
all the categories list in view (form) but when i select some of them not save in database. 所有类别都在视图(窗体)中列出,但是当我选择其中一些时,不会保存在数据库中。 in rails console i do this
在Rails控制台中,我这样做
p = InternetProduct.find(5)
p.categories = Category.find(1,2,3)
this save to database without any problem, what should i do ? 这可以毫无问题地保存到数据库中,该怎么办? tanks for reading this
读这本书的坦克
I found solution to solve this. 我找到解决方案。 when we use has_and_belong_to_many or any other relation , if you want to use collection select in simple_form , in the model also should be add this command for nesting form
当我们使用has_and_belong_to_many或任何其他关系时,如果要使用simple_form中的collection select,则在模型中还应添加此命令以嵌套表格
accepts_nested_attributes_for :categories
also in the controller in related method for example in the new we should 同样在控制器中的相关方法中,例如在新的
def new
@internet_product = InternetProduct.new
@internet_product.categories.build
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.