【发布时间】:2026-01-25 21:45:02
【问题描述】:
我有以下设置。
1 个产品有许多 product_types。 许多 product_types 有 1 种类型。 根据我对文档的理解,HABTM 关系。
我的模型是
class Product < ApplicationRecord
has_and_belongs_to_many :types
end
class Type < ApplicationRecord
has_and_belongs_to_many :products
end
我有一个这样的连接表迁移
class CreateJoinTableProductTypes < ActiveRecord::Migration[5.1]
def change
create_join_table :products, :types do |t|
t.index :product_id
t.index :type_id
end
end
end
我已经创建了一个表单 - 希望可以正确创建,现在我在表单提交时发送了以下参数:
"product"=>{"name"=>"Product A", "description"=>"A cool product", "image_dir_path"=>"./",
"type"=>{"id"=>"1"}},"commit"=>"Create Product"}
我想知道 1) 在表单和控制器中提交用于创建产品的参数的最佳/rails 约定是什么?
和
2) 我如何/如何获得插入连接表的记录?
我有以下获取参数的方法
def product_params
params.require(:product).permit(:name, :description, :image_dir_path, :type,)
end
但即便如此,我也可以在日志中看到 :type 的 unpermitted 参数
目前我的控制器只有:
@product = Product.new(product_params)
我将非常感谢有关创建此对象的 rails 方式的任何建议。我已经阅读了 HABTM 的 api 文档,但没有看到任何关于模型对象或我应该如何在控制器中处理这些东西的内容。
谢谢!
【问题讨论】:
-
产品中没有
type。你有很多类型。您可以将type_ids: [ ]添加到product_params.,这是一个类型id 的数组。
标签: ruby-on-rails model controller has-and-belongs-to-many jointable