【问题标题】:Is there a better way to do this? i.e. Chain the named scopes more nicely有一个更好的方法吗?即更好地链接命名范围
【发布时间】:2011-05-04 17:48:14
【问题描述】:

此代码运行良好,但我正在查看它并认为它可以更清洁。也许有一种更惯用的 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)

【问题讨论】:

    标签: ruby-on-rails ruby named-scope method-chaining


    【解决方案1】:

    清理这种情况的一种方法是使用滑动范围机制,您可以使用相同的变量一次移动范围:

    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)
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-03
      • 2011-06-30
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      • 2023-01-31
      • 2014-12-17
      相关资源
      最近更新 更多