如何结合.order的范围?

时间:2017-05-21 09:46:13

标签: ruby-on-rails ruby model-view-controller scope

在控制器......

@challenges = @user.challenges.last_10 # I'd like to combine into one scope

在模型中......

  scope :accomplished, -> { where(accomplished: true) }
  scope :unaccomplished, -> { where(accomplished: nil) }
  scope :last_10, -> do
    order("deadline DESC").accomplished.limit(10)
    order("deadline DESC").unaccomplished # No Limit on Rendering Unaccomplished Challenges
  end

在视图中......

<% @challenges.each do |challenge| %>
  <%= challenge.name %>
<% end %>

如何列出所有unaccomplished个问题,但限制在过去10个accomplished个问题?

这样我可以渲染这样的东西......

Accomplished Challenge
Accomplished Challenge
Accomplished Challenge
Accomplished Challenge
Accomplished Challenge
Accomplished Challenge
Accomplished Challenge
Accomplished Challenge
Accomplished Challenge
Accomplished Challenge # If User Has 10 or More Accomplished Challenges Stop Here
Unaccomplished Challenge # List All Unaccomplished Challenges
Unaccomplished Challenge... etc...

2 个答案:

答案 0 :(得分:2)

这个怎么样,

scope :accomplished, -> { where(accomplished: true) }
scope :unaccomplished, -> { where(accomplished: nil) }
scope :descending, -> { order('deadline desc') }
scope :last_10, -> { accomplished.limit(10) + unaccomplished }

然后在你的控制器中,

@user.challenges.descending.last_10

大多数情况下这应该有用,需要注意的是它会返回Array而不是Activerecord Array

希望有所帮助......

答案 1 :(得分:0)

您可以在原始SQL中执行此操作,但请注意布尔测试因数据库类型而异,您可能希望查找数据库的正确格式...这也适用于大多数数据库返回数组。 / p>

query = <<-SQL 
  SELECT * 
  FROM payment_details
  (WHERE accomplished = 1 ORDER BY deadline DESC LIMIT 10) OR
  (WHERE accomplished <> 0) 
  ORDER BY deadline DESC 
SQL

result = ActiveRecord::Base.connection.execute(query)