根据我的应用,我需要根据一系列条件获取用户。
@usersSet1 = XXX based on a bunch of conditions
@usersSet2 = XXX based on a bunch of different conditions
@usersSet3 = XXX based on a bunch of even more different conditions
然后我想结合3,并取得前100名记录。有关使用Rails完成此操作的任何想法?感谢
答案 0 :(得分:3)
您应该在模型中定义范围:
# model
scope :set1, where(some_conditions), ...
scope :set2, where(some_conditions), ...
scope :set3, where(some_conditions), ...
scope :top_100, limit(100)
为这些范围指定适当的名称。当然,你需要通过某种东西来order
。
然后你可以打电话:
@usersSet1 = User.set1
@usersSet2 = User.set2
@usersSet3 = User.set3
@usersset123 = User.set1.set2.set3.top_100
它将AND
set1,set2和set3中的所有条件。
答案 1 :(得分:-1)
最好的方法是执行一次SQL查询,撤回具有这些条件的字段。例如:
@users = User.all(select => "city,state,last_name,first_name,…", :limit => 100)
现在你拥有了所有的专栏。所以你继续:
@usersSet1 = @users.select{|a| a.state == 'Charlotte' && a.state == 'NC') #pulls back users in Charlotte
@usersSet2 = @users.select{|b| b.last_name == 'Smith' } #pulls back users that have the last name of Smith.
@usersSet3 = @users.select{|b| b.first_name == ('John' || 'Joe') } #pulls back users that have the first name of John or Joe.
依此类推......在我看来,这更具可扩展性。