Controller code could be like following:
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
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'}}
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 %>
I have used collection_select you can even use other select helpers.
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' %>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…