【问题标题】:Sending arrays of arrays as parameter and then again looping though each array将数组数组作为参数发送,然后再次循环遍历每个数组
【发布时间】:2014-09-10 13:49:04
【问题描述】:

我有一个场景,我向所有用户发送通知邮件。因此我需要获取所有信息,例如 useremail、videocount、imagecount、videoids、imageids 等并发送到 usermailer 以发送邮件。我想简化这个过程通过将所有必需的参数发送到方法并再次循环遍历每个数组。

    for example:-

    ###########the below code is in a loop of users################

    User.signed_in_users.find_in_batches(:batch_size => 100 ) { |users| users.each { |user| 

    vcount=Video.where(:users_notified=>f).count
    icount=Image.where(:users_notified=>f).count
    acount=Audio.where(:users_notified=>f).count

    @count << vcount + icount + acount

    vcat=###ALL VIDEO CATEGORIES
    icat=###ALL IMAGE CATEGORIES
    acat=###ALL AUDIO CATEGORIES

    @cats << vcat + icat + acat...and many more


   ###########now sending all these parameter to mailer(array of arrays)
   ####how i can simplify this call 
UserMailer.notify_user(user.email,@video_cat,@video_count,@image_cat,@image_count,@audio_cat,@audio_count,@place_cat,@place_count,@Lpage_count,@Dpage_count).deliver


    } } ###loop ends

【问题讨论】:

  • 所有模型和用户之间是否有任何关系。喜欢一对多?
  • 是的,他们有通常的 has_many 和 belongs_to .. @NitinVerma

标签: ruby-on-rails arrays ruby-on-rails-3 ruby-on-rails-3.2 actionmailer


【解决方案1】:

我不知道您为什么要多次尝试获取相同的值。您的以下代码无缘无故地运行了多次。

vcount=Video.where(:users_notified=>f).count
icount=Image.where(:users_notified=>f).count
acount=Audio.where(:users_notified=>f).count

@count << vcount + icount + acount

vcat=###ALL VIDEO CATEGORIES
icat=###ALL IMAGE CATEGORIES
acat=###ALL AUDIO CATEGORIES

@cats << vcat + icat + acat

因为您正在迭代 user 对象。而且这一堆代码中没有user的交互。所以你可以把它从你的每个块中拿出来:

vcount=Video.where(:users_notified=>f).count
icount=Image.where(:users_notified=>f).count
acount=Audio.where(:users_notified=>f).count

@count << vcount + icount + acount

vcat=###ALL VIDEO CATEGORIES
icat=###ALL IMAGE CATEGORIES
acat=###ALL AUDIO CATEGORIES

@cats << vcat + icat + acat

User.signed_in_users.find_in_batches(:batch_size => 100 ) { |users| users.each { |user| 

###########now sending all these parameter to mailer(array of arrays)
  UserMailer.notify_user(user.email,@count,@cats)

} } ###loop ends

【讨论】:

  • 对不起@Nitin Verma,,,,它可能看起来令人困惑..为了简化,我已经删除了代码的复杂部分....我已经更新了我的问题
  • 只是为了确认。此块是否对用户对象 vcount=Video.where(:users_notified=&gt;f).count icount=Image.where(:users_notified=&gt;f).count acount=Audio.where(:users_notified=&gt;f).count @count &lt;&lt; vcount + icount + acount vcat=###ALL VIDEO CATEGORIES icat=###ALL IMAGE CATEGORIES acat=###ALL AUDIO CATEGORIES @cats &lt;&lt; vcat + icat + acat 有任何依赖关系
猜你喜欢
  • 2018-07-11
  • 1970-01-01
  • 2019-07-10
  • 1970-01-01
  • 1970-01-01
  • 2021-07-15
  • 2014-06-04
相关资源
最近更新 更多