Rails - Create a new category (Could not find a category with an identifier)

I have an application in which I know

def new respond_to do |format| format.html { new_or_edit } format.js { @category = Category.new } end end 

gets called when I click the link.

This results in a call to new_or_edit (defined in the same file).

  def new_or_edit @categories = Category.find(:all) @category = Category.find(params[:id]) @category.attributes = params[:category] if request.post? respond_to do |format| format.html { save_category } format.js do @category.save @article = Article.new @article.categories << @category return render(:partial => 'admin/content/categories') end end return end render 'new' end 

After some tests, I found that every execution stops at

 @category = Category.find(params[:id]) 

with the error "Could not find category without identifier." Params didn't have: id hash when I printed it. This is because I have to save it in the database before the default field is created: id?

+4
source share
1 answer

What you are doing wrong is trying to combine two different actions: new and edit.

params is a hash of parameters that you receive from the client.

When creating a new object, params[:id] remains empty, since the id attribute of the newly created object is the responsibility of the server, not the client.

When you edit an existing object, params[:id] not empty, since the object already exists in the database and has an identifier. The meaning of params[:id] here: "Please edit the object with id param [: id] using these attributes."

After explaining this, when you create the new object, this line:

 @category = Category.find(params[:id]) 

Failure with params[:id] empty.

+3
source

Source: https://habr.com/ru/post/1441052/


All Articles