开发者

rails to_json not following scropes

When I just the to_json method it seems to ignore all other options... any ideas how to fix this?

var places = <%=raw @location_for_map.limit(5).to_json(:only => [:name, :lat, :lng]) %>;

I'm trying to plug in points from json on a google map, but noticed the points never got smaller with any of my scopes. where, order, limit...

I could put a limit(5) and it would still return 1000 records regardless.

The controller looks something like this:

sort = case params[:sort]
       when "name" then session[:sort] = "name"
       when "min_price" then session[:sort] = "min"
       when "avg_price" then session[:sort] = "cache_price"
       when "rating" then session[:sort] = "cache_rating DESC NULLS LAST"
       end

@locations = Location.find(params[:id])       
@base = @locations.places.active

#@location_for_map = @locations.places.limit(5)

unless params[:tags].blank?
  @base = @base.tagged_with(params[:tags])
end

unless params[:price_high].blank?
  price_high = (params[:price_high].to_f * Currency.rate(params[:currency]))
  price_low = (params[:price_low].to_f * Currency.rate(params[:currency]))
  @base = @base.where("cache_price BETWEEN ? AND ?",price_low,price_high)
end

@base = @base.order(session[:sort])

#@location = @locations.places.active.paginate :page => params[:page]
@location = @base.paginate :page => par开发者_开发技巧ams[:page]
@location_for_map = @base


I'm not sure how to_json behaves on collections that haven't fully been enumerated yet. It's probably a bug that it ignores your applied scopes, but this might work better:

@location_for_map.limit(5).all.to_json(:only => [:name, :lat, :lng])

@location_for_map.limit(5) doesn't actually return an array; it returns an object that represents all the scopes applied so far, and only actually fetches the array of results when you start treating that object like an array.

Applying the all method forces Rails to fetch the results immediately, and to_json probably knows better how to work with the actually array than the placeholder object. (All my guess, but give it a go, regardless.) Might be worth seeing if there's a bug report yet, and, if not, filing one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜