2012-07-11 51 views
0

我来自一个PHP世界,对Ruby来说很新,所以可能有更好的方法来做到这一点。用更好的代码可以更简洁地表达这个块吗?这个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”部分,但如果有更好的方法去解决这个问题,我很乐意开悟。

编辑 我在Mongoid中使用MongoDB,所以连接不会成为我的选择。

+1

'LeadSinger.find(Band.where(:类型=>“摇滚).pluck(: id))。update_all(:rock_and_roll => true)' – MurifoX 2012-07-11 20:16:33

回答

3

随着MongoId你应该仍然能够与指标分析更新:

LeadSigner.where(:band_id.in => band_ids).update(:rock_and_role => true) 
+0

您是否应该在此添加多标志? – 2012-07-11 20:19:38

+0

使用scope.update,mongoid应该设置多标志本身。 – gmalette 2012-07-11 20:22:57

+0

啊,这是新的版本:) – 2012-07-11 20:24:36

4

ActiveRecord的答案(问题更新之前,我希望仍然有用):make associations:band has_one:lead_signer,LeadSinger belongs_to:band。现在:

LeadSinger.joins(:band).where(:"bands.type" => 'Rock & Roll'). 
    update_all(:rock_and_roll => true) 
+0

我喜欢update_all,但我应该提到我在使用MongoDB w/Mongoid并且不能使用连接 – jbnunn 2012-07-11 20:13:50

+0

@jnunn:如果你不提及ORM它被假定为AR。然后更新问题。不过,我没有使用MongoDB的经验。 – tokland 2012-07-11 20:16:05

+0

感谢@tokland,它现在已经更新 - 仍然在提高您的答案 – jbnunn 2012-07-11 20:16:22