繁体   English   中英

rails:关联表(has_and_belongs_to_many)不保存任何记录

[英]rails : association tabel (has_and_belongs_to_many) not save any record

我使用rails 5,简单的形式。 在我的应用程序中,有一个类别模型和一个OnlineProduct模型。 我不知道为什么要在我的OnlineProduct关联表中添加一些类别时保持空白且不更改。

类别模型:

class Category < ApplicationRecord

  has_ancestry

  has_and_belongs_to_many :internet_products

end

互联网产品型号:

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 %>

所有类别都在视图(窗体)中列出,但是当我选择其中一些时,不会保存在数据库中。 在Rails控制台中,我这样做

 p = InternetProduct.find(5)
 p.categories = Category.find(1,2,3)

这可以毫无问题地保存到数据库中,该怎么办? 读这本书的坦克

我找到解决方案。 当我们使用has_and_belong_to_many或任何其他关系时,如果要使用simple_form中的collection select,则在模型中还应添加此命令以嵌套表格

  accepts_nested_attributes_for :categories  

同样在控制器中的相关方法中,例如在新的

def new
  @internet_product = InternetProduct.new
  @internet_product.categories.build
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM