Created
February 1, 2016 12:38
-
-
Save IvikGH/442f932f5eac7cc6f642 to your computer and use it in GitHub Desktop.
Need HELP with 340 RailsCast
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ProductsDatatable | |
delegate :params, :h, :link_to, :number_to_currency, to: :@view | |
def initialize(view) | |
@view = view | |
end | |
def as_json(options = {}) | |
{ | |
sEcho: params[:sEcho].to_i, | |
iTotalRecords: Product.count, | |
iTotalDisplayRecords: products.total_entries, | |
aaData: data | |
} | |
end | |
private | |
def data | |
products.map do |product| | |
[ | |
link_to(product.name, product), | |
h(product.category), | |
h(product.released_on.strftime("%B %e, %Y")), | |
number_to_currency(product.price) | |
] | |
end | |
end | |
def products | |
@products ||= fetch_products | |
end | |
def fetch_products | |
products = Product.order("#{sort_column} #{sort_direction}") | |
products = products.page(page).per_page(per_page) | |
if params[:sSearch].present? | |
products = products.where("name like :search or category like :search", search: "%#{params[:sSearch]}%") | |
end | |
products | |
end | |
def page | |
params[:iDisplayStart].to_i/per_page + 1 | |
end | |
def per_page | |
params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10 | |
end | |
def sort_column | |
columns = %w[name category released_on price] | |
columns[params[:iSortCol_0].to_i] | |
end | |
def sort_direction | |
params[:sSortDir_0] == "desc" ? "desc" : "asc" | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ProductsController < ApplicationController | |
def index | |
respond_to do |format| | |
format.html | |
format.json { render json: ProductsDatatable.new(view_context) } | |
end | |
end | |
def show | |
@product = Product.find(params[:id]) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h1>Products</h1> | |
<table id="products" class="display" data-source="<%= products_url(format: "json") %>"> | |
<thead> | |
<tr> | |
<th>Product Name</th> | |
<th>Category</th> | |
<th>Release Date</th> | |
<th>Price</th> | |
</tr> | |
</thead> | |
<tbody> | |
</tbody> | |
</table> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment