简体   繁体   中英

ActionController::UnknownFormat while using javascript format in respond_to

I am building my first app which uses javascript as a response to controller action request. I've defined create action like this inside my controller:

def create
    @cat = Cat.new(cat_params)

    respond_to do |format|
      if @cat.save
        format.js
      end
    end
end

And I've created create.js.erb inside views/cats which has a code for response. After I trigger create action inside my view, I receive the following error:

ActionController::UnknownFormat in CatsController#create
ActionController::UnknownFormat

How to deal with this problem? What do you recommend? I am using Rails4

It's possible you are getting that error because you don't have a format if @cat doesn't save. This should work for you:

def create
  @cat = Cat.new(cat_params)

  respond_to do |format|
    if @cat.save
      format.js
    else
      #assuming that you are using js throughout
      format.js { render :new }
    end
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM