Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

ruby on rails - How to call Select_tag in Create action

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' %>

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

But when I create My product An error occurs that category Should be Present. I think that params[:category] not pass the category_id

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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' %>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...