Oleg  Vidyaev Oleg Vidyaev - 2 months ago 12
Javascript Question

"ActionController::UnknownFormat" as a result of using AJAX with format.js

I have models: idea,item,product.
I'm trying to add Products to Ideas through Items in a view of Idea's editing.
My edit.html.erb - Idea

<div id="items">
<%= render @idea.items %>
</div>

<div class="products">
<% @products.each do |p| %>
<%= p.title %><%= button_to '+', items_path(product_id: p.id, idea_id: @idea.id), remote: true %>
<% end %>
</div>


My items controller:

def create
product = Product.friendly.find(params[:product_id])
@item = @idea.add_product(product.id)

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


idea.rb

def add_product(product_id)
item = items.find_by(product_id: product_id)
if item
else
item = items.build(product_id: product_id)
end
item
end


My "create.js.erb"

$('#items').html("<%= escape_javascript render(@idea.items) %>");


When I put "format.html {redirect_to :back}" in def create (items_controller) everything goes OK, but without AJAX=(

Logs


Completed 406 Not Acceptable in 91ms

ActionController::UnknownFormat (ActionController::UnknownFormat):

app/controllers/items_controller.rb:33:in `create'


Help me, guys. I have googled the whole internet

Answer

For those who are still googling... It helped me to specify defaults: => {format: 'js'} for ajax actions in routes.rb.

post 'myaction' => 'mycontroller#myaction', defaults: { format: 'js' }
Comments