javascript - Better way to use a json object in a Rails application -
in rails app have many categories have many clients. supports switching languages.
the categories shown in navigation of app , want make custom dropdown contains clients of category. created when user hovers on of categories.
i've created new resource doing job of fetching clients belong hovered category, i'm having trouble making clients linkable due internationalization.
this javascript code:
$(function () { $(".nav_category").hover(function () { category_dropdown = $(this).children(".category_dropdown"); clients_from_category = category_dropdown.children(".clients_from_category"); category_dropdown.toggle(0, "hidden"); $.get($(this).data("url"), function(response) { client_name = response[0]['translations'][0]['name']; client_picture = response[0]['pictures'][0]['image']['thumb']['url']; html = "<a href='/clients/"+response[0]['id']+"' class='nearest_client'>"; html += "<img src='" + client_picture +"'>"; html += client_name; html += "</a>"; clients_from_category.html(html); }); }, function() { $(this).children(".category_dropdown").toggle(0, "hidden"); }) });
the problem here links displayed this:
<a href="/clients/157" class="nearest_client"> <img src="/uploads/picture/image/361/thumb_image.jpg">client name </a>
notice there no locale set. should like:
<a href="en/clients/157">
is there way set locale? or approaching problem in bad way? better way of setting listener on div , creating needed dom elements returned json object?
the solution use rails link helpers add url or path json output.
if using jbuilder (which installed default):
# /app/clients/views/show.json.jbuilder json.id @client.id json.name @client.name json.path client_path(@client) json.url client_url(@client)
but recommend using activemodel::serializers:
class clientserializer < activemodel::serializer attributes :id, :name, :path, :url def url client_url(object) end def path client_path(object) end end
see the railscast basic use instructions.
then use in javascript so:
$(function () { $(".nav_category").hover(function () { var category_dropdown = $(this).children(".category_dropdown"); var clients_from_category = category_dropdown.children(".clients_from_category"); var category_dropdown.toggle(0, "hidden"); $.get($(this).data("url"), function(response) { var client = response[0]; var client_name = client['translations'][0]['name']; var client_picture = client['pictures'][0]['image']['thumb']['url']; var html; html = "<a href='+ client.url +' class='nearest_client'>"; html += "<img src='" + client_picture +"'>"; html += client_name; html += "</a>"; clients_from_category.html(html); }); }, function() { $(this).children(".category_dropdown").toggle(0, "hidden"); }) });
on side note - need use var keyword when declaring variables in javascript. otherwise created globals bad thing. use jslint or strict mode catch misstakes this.
Comments
Post a Comment