如何在创建操作中调用 Select_tag [英] How to call Select_tag in Create action
问题描述
实际上我从类别中获取我的类别模型值以获取输入.....category_id 在产品模型中充当外键我正在接受这样的输入
Actually im getting my category model values from category to take input..... category_id act as a foreign key in Product Model I am taking input like this
<%= select_tag 'category', options_for_select(Category.pluck(:name, :id)), class: 'form-control', id: 'sel1' %>
并在 Product_controller 中传递类别 ID 创建这样的操作
And Pass Category Id in Product_controller Create action like this
def create
@product = Product.new(product_params)
@product.user = current_user
private
def product_params
params.require(:product).permit(:productname, :productprice, :productstatus,:image ,:category )
end
但是当我创建我的产品时发生错误,该类别应该存在.我认为 params[:category] 没有通过 category_id
But when I create My product An error occurs that category Should be Present. I think that params[:category] not pass the category_id
推荐答案
控制器代码如下:
def create
@product = Product.new(product_params)
@product.user = current_user
@product.save
end
private
def product_params
params.require(:product).permit(:productname, :productprice, :productstatus, :image, :category_id)
end
查看代码如下:
理想情况下,您的 category_id
应该出现在 params[:product]
中您的参数应该类似于 {product: {category_id: 1, other_attr: 'abc'}}
View code will be as following:
Ideally your category_id
should come in params[:product]
Your params should look like {product: {category_id: 1, other_attr: 'abc'}}
您必须使用 form_for
或 form_with
,因此请使用您的 formbuilder 对象.
You must be using form_for
or form_with
so use your formbuilder object.
<%= form_with(model: @product) do |f| %>
<%= f.collection_select :category_id, Category.all, :id, :name, class: 'form-control', id: 'sel1' %>
<% end %>
我使用了 collection_select 你甚至可以使用其他选择助手.
I have used collection_select you can even use other select helpers.
另一种解决方法可能是使用名称属性作为 product[category_id]
Another workaround could be using name attribute as product[category_id]
<%= select_tag 'category', options_for_select(Category.pluck(:name, :id)), name: 'product[category_id]', class: 'form-control', id: 'sel1' %>
这篇关于如何在创建操作中调用 Select_tag的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!