在Rails 3应用程序的电子邮件中包含控制器方法?

时间:2012-04-30 12:07:51

标签: ruby-on-rails-3 email controller actionmailer

我正在尝试通过电子邮件发送月度报告,这个报告与当前月份的收入相比很简单。

我的所有这些工作都在我的报告控制器中(引用另一个名为Clinical的模型):

# Clinical income by month report
@clinical_income_by_month = Clinical.select(%q{date_format(transactiondate, '%Y') as year, date_format(transactiondate, '%M') as month, sum(LineBalance) as income})
                               .where(:payments => 0)
                               .where('linebalance <> ?', 0)
                               .where('analysiscode <> ?', 213)
                               .group(:monthyear)

然后我对该表的部分内容包含数据:

<div class="row">
    <div class="twelve columns"><h5>This months income so far is <span style="font-size:1.2em"class="<% if @clinical_income_by_month.first.income >= @clinical_income_by_month.first(:offset => 12).income %>green<% else %>red<% end %> radius label"><%= number_to_currency(@clinical_income_by_month.first.income, :unit => "&pound;", :separator => ".", :delimiter => ",") %></span></h5> <%= @clinical_income_by_month.first.month %> <%= @clinical_income_by_month.first(:offset => 12).year %>'s income was <%= number_to_currency(@clinical_income_by_month.first(:offset => 12).income, :unit => "&pound;", :separator => ".", :delimiter => ",") %>.</div>
  </div>
<hr />

<table>
  <tr>
    <th>Year</th>
    <th>Month</th>
    <th>Income</th>
  </tr>  
  <% @clinical_income_by_month.each do |c| %>
  <tr>
    <td><%= c.year %></td>
    <td><%= c.month %></td>
    <td><%= number_to_currency(c.income, :unit => "&pound;", :separator => ".", :delimiter => ",") %></td>
  </tr>    
  <% end %>
</table>

我希望能够将这部分内容纳入我的电子邮件中,或者如果不可能,我想显示最后收入的价值。

<%= @clinical_income_by_month.first.income %>

我的电子邮件代码如下所示:

Finance Report
================================================
<%= number_to_currency(@clinical_income_by_month.first.income) %>

我得到的错误是:

1.9.2-p318 :009 > UserMailer.finance_report().deliver
ActionView::Template::Error: undefined method `first' for nil:NilClass
from   /Users/dannymcclelland/Projects/premvet/app/views/user_mailer/finance_report.text.erb:3:in  `_app_views_user_mailer_finance_report_text_erb___4501411113534248604_70358523362460'

当我从标准方法中提取值时,它会起作用:

<%= number_to_currency(Clinical.first.UserID) %>

但不是我从我创建的@clinical_income_by_month报告中调用它。

任何指针都将不胜感激!

2 个答案:

答案 0 :(得分:3)

你需要做这样的事情:

user_mailer.rb中的

def finance_report(clinical_income_by_month)

  @clinical_income_by_month = clinical_income_by_month

  ... # all you had here before

end

控制器中的 以这种方式调用它:

UserMailer.finance_report(@clinical_income_by_month).deliver

答案 1 :(得分:0)

显然你的@clinical_income_by_month是零。这意味着select查询不会像您认为的那样返回值。这是一个模型问题。您应该启动“rails console”并查看查询是否返回所需的值,而不是检查视图。