我有一個客戶端模型和我的控制器中應該返回最近的客戶端的方法。我使用ActiveModel :: Serializer,但它不起作用。ActiveModel :: Serializer不工作
class ClientSerializer < ActiveModel::Serializer
attributes :id, :name, :path, :url
def url
client_url(object)
end
def path
client_path(object)
end
end
控制器:
def nearby_from_category
@closest_clients = Client.from_category(params[:category]).
activated.locateable.all_with_translation(@lang).
by_distance(origin: remote_ip).limit(2)
render json: @closest_clients.to_json(include: {
translations: {only: [:name, :content]},
pictures: {only: :image}
})
end
的javascript:
$(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");
})
});
該得到的HTML輸出是這樣的:
<a href="undefined" class="nearest_client"><img src="/uploads/picture/image/361/thumbimage.jpb</a>
maxcal和Gavin都是對的,但我接受了maxcal的答案,因爲他是第一個。感謝這兩個! –
其實加文打我40秒:) – max
是的,但你和我在前面的問題做了一個交易:) 對不起加文! –