0

我来自 PHP 世界,对 Ruby 很陌生,所以可能有更好的方法来做到这一点。这个块可以用更好的代码更简洁地表达吗?

bands = Band.where(:type => 'Rock & Roll').only(:id)
band_ids = bands.map &:id

band_ids.each do |id|
  lead_singer = LeadSinger.find(:band_id => id)
  if lead_singer
    lead_singer.rock_and_roll = true
    lead_singer.save
  end
end

这一切都感觉有点臃肿。如果没有找到结果,我添加了“if lead_singer”部分,但如果有更好的方法来解决这个问题,我很想得到启发。

编辑 我将 MongoDB 与 Mongoid 一起使用,因此我不会选择加入。

4

2 回答 2

4

ActiveRecord 的答案(在问题更新之前,我希望仍然有用):进行关联:乐队 has_one :lead_signer, A LeadSinger belongs_to :band。现在:

LeadSinger.joins(:band).where(:"bands.type" => 'Rock & Roll').
  update_all(:rock_and_roll => true)
于 2012-07-11T20:13:01.580 回答
3

使用 MongoId,您仍然应该能够使用标准进行更新:

LeadSigner.where(:band_id.in => band_ids).update(:rock_and_role => true)
于 2012-07-11T20:17:55.867 回答