Ruby技术问题:如何仅展示积分≤50的Reward数据
调整Ruby代码实现仅返回符合积分条件的奖励数据
我来帮你修正这段代码,让它直接返回积分符合要求的奖励数据,而不是返回所有奖励并标记是否符合。
原代码的问题
你当前的代码是先取出所有奖励,然后生成一个哈希来记录每个奖励是否满足积分条件,但这和需求不符——我们需要的是只保留符合条件的奖励条目,而非全部标记。
优化后的代码(推荐数据库层面筛选)
直接在数据库层面过滤符合条件的奖励,这比先查所有数据再在内存中过滤要高效得多,尤其当奖励数据量大的时候:
def index @user = User.find_by_id(1) user_point = @user.point # 根据你的需求二选一: # 1. 如果是获取积分≤50的奖励: # @eligible_rewards = Reward.where('point <= 50') # 2. 如果是获取积分≤用户当前积分的奖励(和你原代码逻辑对齐): @eligible_rewards = Reward.where('point <= ?', user_point) @http_status = 200 @http_response = { status: true, # 可以指定返回的字段,避免返回冗余数据,比如只返回id、point、奖励名称等 results: @eligible_rewards.as_json(only: [:id, :point, :name]) } render json: @http_response, status: @http_status end
关键调整点说明
- 数据库层面筛选:用
Reward.where直接过滤,减少数据库传输的数据量和内存占用,性能更好 - 直接返回有效数据:不再生成标记哈希,而是直接返回符合条件的奖励对象,完全匹配需求
- 简化响应构建:直接用哈希字面量构建
@http_response,避免未初始化变量的潜在问题 - 可选字段控制:用
as_json(only: [...])可以指定返回的字段,让接口返回更简洁
内存过滤方案(不推荐,仅作参考)
如果因为特殊原因需要先取出所有奖励再在内存中过滤,可以用select方法:
def index @user = User.find_by_id(1) user_point = @user.point @rewards = Reward.all # 筛选出积分符合条件的奖励 @eligible_rewards = @rewards.select { |reward| reward.point <= user_point } @http_status = 200 @http_response = { status: true, results: @eligible_rewards.as_json(only: [:id, :point, :name]) } render json: @http_response, status: @http_status end
内容的提问来源于stack exchange,提问作者Sophia De Leon
相关产品推荐
相关产品推荐

