2010-02-02 13 views
0

我想在rails的某個時候使用Whenever插件來執行模型進程。試圖發送郵件給多個用戶時出現Rails錯誤

當我嘗試在我的用戶模型中使用mail_out進程時,出現以下錯誤。有人能請我指出發生了什麼問題的正確方向嗎?

/var/lib/gems/1.8/gems/rails-2.3.5/lib/commands/runner.rb:48: /var/lib/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:380:in `load_without_new_constant_marking': /home/tnederlof/Dropbox/Ruby/daily_trailer/app/models/user.rb:9: syntax error, unexpected tIDENTIFIER, expecting ')' (SyntaxError) @users = find(:all, :conditions => "#{weekday}sub = "t"") 

我schedule.rb如下:

every 1.day, :at => '5:30 am' do 
    runner "User.mail_out" 
    end 

我的用戶模型爲:

class User < ActiveRecord::Base 

    acts_as_authentic 

    def self.mail_out 

    weekday = Date.today.strftime('%A').downcase 

    @users = find(:all, :conditions => "#{weekday}sub = t") 


    @users.each { |u| UserMailer.deliver_mail_out(u)} 


    end 

end 

我user_mailer文件是:

class UserMailer < ActionMailer::Base 
    def mail_out(users) 
    @recipients = { } 
    users.each do |user| 
     @recipients[user.email] = { :name => user.name } 
    end 


    from  "[email protected]" 
    subject  "Check out the trailer of the day!" 
    body  :user => user 
    end 

end 

遷移:

create_table "users", :force => true do |t| 
    t.string "email" 
    t.date  "birthday" 
    t.string "gender" 
    t.string "zipcode" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    t.string "crypted_password" 
    t.string "password_salt" 
    t.string "persistence_token" 
    t.string "mondaysub",   :default => "f", :null => false 
    t.string "tuesdaysub",  :default => "f", :null => false 
    t.string "wednesdaysub",  :default => "f", :null => false 
    t.string "thursdaysub",  :default => "f", :null => false 
    t.string "fridaysub",   :default => "f", :null => false 
    t.string "saturdaysub",  :default => "f", :null => false 
    t.string "sundaysub",   :default => "f", :null => false 
    end 

回答

1

改變這一行

@users = find(:all, :conditions => "#{weekday}sub = t") 

@users = find(:all, :conditions => ["#{weekday}sub = t"]) 

用於查找方法的條件鍵採取任一個數組或哈希作爲值。如果你正在使用數組,那麼數組的第一個元素會直接轉換成「where」子句的sql語句,如果你沒有任何問號的話,那麼這些問號就會被數組的其他元素所替代。例如,改變上述質疑標誌符號將成爲

@users = find(:all, :conditions => ["#{weekday}sub = ?", 't']) 

當「T」是一個字符串

其更好地使用問號符號,因爲它是更安全,因爲你不這樣做串插在你的sql字符串中,這可能對你的應用程序數據非常有害。

你也可以寫你的查詢哈希條件,像這樣

@users = find(:all, :conditions => {"#{weekday}sub".to_sym => 't'}) 

大多數人都喜歡在這個數組方式,換句話說認爲這是做它的軌道的方式。

另一點,看你UserMailer#mailout方法,你不需要做

@users.each { |u| UserMailer.deliver_mail_out(u)} 
在User.mailout方法

,你可以做

UserMailer.deliver_mail_out(@users) 

因爲你已經從UserMailer#mailout中的users數組中提取每個用戶對象並將它們添加到收件人中。

+0

謝謝,你對我的解釋非常有幫助。完美的感覺! – 2010-02-02 14:05:15

相關問題