ruby on rails——有更好的方法吗?例如,将命名的作用域连接起来



这段代码工作得很好,但我看着它,认为它可以更干净。也许有一种更习惯的ruby/rails方法来做到这一点?顺序很重要,因为member_of作用域必须在分页(返回集合而不是作用域)之前的最后一个

这样做的一个好处是很清楚发生了什么

@locations = Location.send(params[:type]) if type_sent_and_valid? #refine to a particular type if present
@locations = (@locations || Location.locatable).near(latlng_params) if latlng_sent? #refine to location
@locations = (@locations || Location).member_of(@interest_group.id).paginate(:page=>params[:page], :per_page=>20)

如果参数字符串是这样的:

?lat=50&lng=150&type=restaurant&page=1

那么它应该产生这个

Location.restaurant.near([50.0,150.0]).member_of(@interest_group).paginate(:page=>1, :per_page=>20)

解决这个问题的一种方法是使用滑动作用域机制,使用相同的变量一次移动一步作用域:

location_scope = Location
if (type_sent_and_valid?)
  location_scope = location_scope.send(params[:type])
end
if (latlng_sent?)
  location_scope = location_scope.locatable.near(latlng_params)
end
location_scope = location_scope.member_of(@interest_group.id)
@locations = location_scope.paginate(:page=>params[:page], :per_page=>20)

可根据需要添加其他条件

最新更新