Ruby on rails 有没有更好的方法来执行类似的操作?

Ruby on rails 有没有更好的方法来执行类似的操作?,ruby-on-rails,ruby,Ruby On Rails,Ruby,我正在尝试列出所有用户的产品,其中标志“通知”设置为零 user.probable_associations.where(:notified => 0).collect{|a| Product.where(:id => a.product_id).collect{|p| p.name}}.to_sentence 在语句中两次使用where和collect方法似乎不是很好。有没有更好的办法 而且,结果是 "[\"Product A\"] and [\"Product B\"]"

我正在尝试列出所有用户的产品,其中标志“通知”设置为零

user.probable_associations.where(:notified => 0).collect{|a| Product.where(:id => a.product_id).collect{|p| p.name}}.to_sentence
在语句中两次使用where和collect方法似乎不是很好。有没有更好的办法

而且,结果是

"[\"Product A\"] and [\"Product B\"]" 
这很难看…我仍然需要删除额外的标点符号[\\] 而不是像这样干净的东西

"Product A and Product B"
根据Rich的回答进行编辑,仍然存在问题,因为通知是关联中的一个字段,而不是产品:

  has_many :probable_associations, -> { where "associations.category = 3"}, class_name: 'Association', before_add: :set_probable_category
  has_many :probable_products, class_name: 'Product', through: :probable_associations, source: :product do
    def not_notified
        select(:name).where(notified: 0)
    end  
  end
我会使用:

这是我的贡献,但是你可以使用@spickermann&@tompave的contobustions和.flatte.to_句子

而不知道可能的关联会做什么,我是否可以将代码重写为如下内容:

product_ids = user.probable_associations.where(:notified => 0).map(&:product_id)
Product.where(:id => product_ids).map(&:name).to_sentence
假设可能的关联只是一个ActiveRecord,它有许多关联,并且您希望最终得到产品记录的标题列表,您可以使用以下方法:

ids = user.probable_associations
          .where(notified: 0)
          .pluck(:product_id)

result = Product.where(id: ids).pluck(:name).to_sentence
这与@SpikerMan的答案类似,但pull:column_name比使用块更快,只从DB中提取所需的列

另外,代码生成该字符串的原因是,在调用_语句时,已经有了一个子数组数组。每个子数组包含一个元素:产品名称

这是因为第二次收集被发送到只包含一条记录的ActiveRecord::Relation


你可以用flatte解决这个问题,但是整个操作可以重构。

可能的关联是Rails的核心功能吗?@echan00什么是可能的关联?写.flatte.到句子而不是.到句子。顺便说一句,这段代码可能会导致对单个产品的大量查询。我建议将其重写为,并尝试在一个查询中加载所有产品。它可以重写,但可能的关联是什么?谢谢回复!我的回答应该会有很大帮助。我认为他需要扁平化来修复他的代码片段,但我会用不同的方式来写。你完全正确-我只是想做一个回答,以展示一种不同的方式来完成他写的内容。最大的问题可能是一个谜团。我认为如果通知是产品的属性,你的答案会很有意义。不幸的是,这个问题并没有说得很清楚。是的,但我认为这样做仍然比他目前的状态要好。我会保持现在的状态,如果OP希望我重构以适应他的结构,我当然会这样做。顺便说一句,如果notified是user的一个属性,我会在user model中使用一个作用域。我正在尝试你的答案。。。好像有问题。我会更新我的问题,让你看看我有什么。。
ids = user.probable_associations
          .where(notified: 0)
          .pluck(:product_id)

result = Product.where(id: ids).pluck(:name).to_sentence