【问题标题】:rails task with parameters带参数的rails任务
【发布时间】:2015-10-12 03:21:57
【问题描述】:

我是 rails 任务的新手,我想在任务中执行并传递参数,然后在循环中说是或否执行其他任务(不取决于 ENV,而是取决于我的“即时”需求)。 这是代码:

我的任务:

namespace :invoices do
  desc "CREATE PDF AND SEND MAIL TASK"
  task create_and_send_pdf: :environment do
    Invoice.all.each do |invoice|
        invoice.create_and_send_pdf({send_invoice: true})
    end
  end
end

我要调用的其他函数:

def create_and_send_pdf(options = {})
    begin
        to_print = self
        ...
        if options[:send_invoice].blank? || options[:send_invoice]
            send_to_customer(to_print) 
        end
        ...

    end

    return true
end


private

    # Call mailer and send mail to customer
    def send_to_customer(invoice)
        unless invoice.send_at
            key = SecureRandom.hex(10)
            # Update invoice attibutes
            invoice.update_attributes({track_number: key, send_at: DateTime.now})
            InvoiceMailer.sample_email(invoice, key).deliver!
        end
    end

还有我的 rake 任务:

rake invoices:create_and_send_pdf

所以这是交易,如果我使用 send_invoice: false 参数执行我的任务,我不想调用 send_to_customer 函数

谢谢

【问题讨论】:

标签: ruby-on-rails task


【解决方案1】:
task :create_and_send_pdf, [:send_invoice] => :environment do |task, args|
  Invoice.all.each do |invoice|
    invoice.create_and_send_pdf({send_invoice: args.send_invoice})
  end
end

rake invoices:create_and_send_pdf[true]
rake invoices:create_and_send_pdf[false]

【讨论】:

  • 感谢您的回复,但它仍然不起作用,我尝试在每个循环中的发票旁边设置 args 然后删除 args.send_invoice 的 send_invoice 以仅获取传递的值,但代码仍然执行其他功能。我的 if 条件有问题吗? ` if options[:send_invoice].blank? ||选项[:send_invoice] `
  • 好吧,这是我的情况,我只是为 || 添加一个 == true options[:send_invoice],谢谢!
猜你喜欢
  • 2014-08-24
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 2018-08-29
  • 2013-09-10
  • 2017-08-02
  • 1970-01-01
相关资源
最近更新 更多