【发布时间】:2016-11-29 11:37:13
【问题描述】:
我使用 rails 5 ,简单的形式。在我的应用程序中有一个 Category 模型和一个 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
互联网产品控制器:
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)
这个保存到数据库没有任何问题,我该怎么办? 阅读本文的坦克
【问题讨论】:
-
你有和
OnlineProduct加入表吗? -
是的。这就是我所拥有的:'class CategoriesInternetBons
-
编辑您的问题并添加此迁移,如果您添加这三个表的表架构,效果会更好。
-
@inye ,我认为数据库模式没有问题,因为在我这样做时在rails控制台中 b = internet_product.find(1) b.categories = Category.find(2,3,4)一切正常。
-
更多信息更容易为您提供帮助
标签: ruby-on-rails associations ruby-on-rails-5 strong-parameters rails-models