有更好的方法吗?即更好地链接命名范围

发布于 2024-11-05 06:08:24 字数 751 浏览 8 评论 0原文

这段代码工作得很好,但我正在查看它并认为它可以更干净。也许有一种更惯用的 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)

如果 params 字符串是这样的: 那么

?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)

This code works fine bu I'm looking at it and thinking it could be cleaner. Perhaps there is a more idiomatic ruby / rails way of doing this? The order is important because the member_of scope has to come last but before the pagination (which returns a collection and not a scope)

The one advantage of this is that it's pretty clear what's happening

@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)

This if a params string was something like this:

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

Then it should yield this

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

坐在坟头思考人生 2024-11-12 06:08:24

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

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)

您可以根据需要添加其他条件。

One way to clean this up is to use a sliding scope mechanism where you move the scope one step at a time using the same variable:

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)

You can add other conditions as required.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文