![](/img/trans.png)
[英]Rails 4 - checkboxes for has_and_belongs_to_many association
[英]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.