【问题标题】:Filtering array with reject + conditions in rails在rails中使用reject +条件过滤数组
【发布时间】:2015-09-27 16:33:19
【问题描述】:

我正在尝试过滤具有多个条件的匹配记录数组,但似乎无法弄清楚,我尝试了很多不同的东西,并在谷歌上搜索了所有内容,但什么都没有......这是代码:

if @post.last_post?
  @recommendations = @course.recommendations_for_subscriber(subscriber, category, language).first(3)
end

和辅助方法

def recommendations_for_subscriber subscriber, category, language
  course_ids = subscriber.courses.pluck(:id)
  recommendations.reject { |c| course_ids.include? c.id }
end

我要做的是将类别和语言作为条件传递给仅具有相同条件集的结果。 “.where” 不起作用,因为它不适用于数组,我似乎无法将它作为拒绝的补充传递。如果我们遇到彼此,任何想法都会非常感激并得到蛋糕奖励!

【问题讨论】:

  • 您收到的错误信息是什么?当前输出的是什么?另外,如果不使用这些值,为什么要将 categorylanguage 传递给 recommendations_for_subscriber 方法?

标签: ruby-on-rails arrays ruby where pluck


【解决方案1】:

我想这会解决你的问题:

def recommendations_for_subscriber subscriber, category, language
  Recommendation.where('courses.id NOT IN(?)', subscriber.courses.pluck(:id))
end

【讨论】:

  • 非常感谢!那工作得很好。虽然我现在感觉有点迟钝。如果你在斯德哥尔摩,请告诉我,我会用蛋糕回报你!
  • 很高兴它成功了。如果我访问斯德哥尔摩,我肯定会从你那里得到蛋糕:)
  • 您也可以使用Recommendation.where.not(courses: { id: subscriber.courses.pluck(:id) }) 消除片段。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-30
  • 2022-01-10
  • 2018-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-04
相关资源
最近更新 更多