Monday, January 19, 2015

Implement best_in_place with Rails

step#1  Gemfile
gem 'best_in_place', github: 'aaronchi/best_in_place'

step#2  application.js
//= require jquery
//= require jquery_ujs
//= require jquery.purr
//= require best_in_place

$(document).ready(function() {
  /* Activating Best In Place */
  jQuery(".best_in_place").best_in_place();
});

For my case i am updating the stock quantity and controllers are inside namespace admin:

step#3 stocks_controller
def index
    @products = Product.all
end

def update
    respond_to do |format|
      if @product.update(product_params)
        format.html { redirect_to [admin, @product], notice: 'Article was successfully updated.' }
        format.json { render :show, status: :ok, location: @product }
      else
        format.html { render :edit }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
 end

step#4 stocks/index.html.erb
<% @products.each do |product| %>
  <%= best_in_place product, :quantity, :type => :input, :path => [:admin, product] %></td>
<% end %>

step#5 products/index.json.jbuilder
json.array!(@products) do |product|
  json.extract! product, :id, :name, :quantity
  json.url admin_product_url(product, format: :json)
end