2

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

Oleg Vidyaev
  • 23
  • 1
  • 4
  • it's likely you need to write the else, or remove if , see http://stackoverflow.com/a/22944769/1197775 – sites Feb 01 '15 at 00:12
  • Try to change `respond_to ... format.js` with `render "create.js.erb"`. Also handle situation when item is not saved – Pavel Evstigneev Feb 01 '15 at 03:46
  • Thank you for advices, but ... I tried to put "else" statement in my def create, but i didn't hepl me, cause statement of saving item was performing. Removing "if" also didn't give me anything. – Oleg Vidyaev Feb 01 '15 at 11:38
  • Pavel, render of "create.js.erb" didn't help me. When i pushed to the button, rails brought me to the page with this code: $('#items').html("\n
  • MDC-4220C
    <\/div><\/form><\/li>\n
  • KIC-301
  • – Oleg Vidyaev Feb 01 '15 at 11:40