2016-02-13 113 views
1

我遵循的軌道上建立一個郵件的紅寶石(指南的網站:https://launchschool.com/blog/handling-emails-in-rails)的指導。控制器梅勒在Ruby on Rails的,活動記錄查詢

我的預覽看起來是這樣的:sample_email.html.erb

<!DOCTYPE html> 
<html> 
<head> 
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' /> 
</head> 
<body> 
<h1>Hi <%= @user.username %></h1> 
<p> 
Sie haben folgende Tags ausgewählt: 
    <% @user.tag_list.each do |tag| %> 
    <%= tag %> <br> 
    <% end %> 

    <br><br> 
    <% @infosall.each do |info| %> #<-- Problem on this line 
     <%= info.name %><br> 
    <% end %><br> 
</p> 
</body> 
</html> 

@ user.username和@ user.tag_list得到呈現,但@infosall不會呈現。我需要在哪裏輸入@infosall,以便它在預覽中呈現?

example_mailer_preview.rb:

# Preview all emails at http://localhost:3000/rails/mailers/example_mailer 
class ExampleMailerPreview < ActionMailer::Preview 
    def sample_mail_preview 
    ExampleMailer.sample_email(User.last) 
    end 
end 

example_mailer.rb:

class ExampleMailer < ApplicationMailer 
    default from: "" 

    def sample_email(user) 
    @user = user 
    mail(to: @user.email, subject: 'Sample Email') 

    end 
end 

users_controller.rb:

class UsersController < ApplicationController 

    def show 
    @user = User.find_by_username(params[:username]) 
    @tags = @user.tag_list 
    @infosall = Array.new 
    @tags.each do |tag| 
     @infosall = @infosall + Info.tagged_with(tag) 
    end 

    @infosall.uniq! 
    @infosall.sort! { |a,b| b.created_at <=> a.created_at } 
    end 

end 

編輯:當我做這example_mailer_preview.rb:

# Preview all emails at http://localhost:3000/rails/mailers/example_mailer 
class ExampleMailerPreview < ActionMailer::Preview 
    def sample_mail_preview 
    ExampleMailer.sample_email(User.last) 

     @user = User.last 
     @tags = @user.tag_list 
     @infosall = Array.new 
     @tags.each do |tag| 
      @infosall = @infosall + Info.tagged_with(tag) 
     end 

     @infosall.uniq! 
     @infosall.sort! { |a,b| b.created_at <=> a.created_at } 
    end 
end 

我得到一個無方法錯誤:未定義的方法`find_first_mime_type」爲#與此代碼:

def find_preferred_part(*formats) 
    formats.each do |format| 
    if part = @email.find_first_mime_type(format) 
     return part 
    end 
    end 

我有什麼錯?任何建議?

回答

1

梅勒是不相關的控制器。當爲某個模型定義show動作時,在您使用該模型渲染某些內容時不會調用它。

想想郵件作爲控制器,設置在其行動中所有需要的實例變量(sample_email在這種情況下)

+0

我在sample_email中添加了一些內容,但出現錯誤(請參閱我的編輯),任何建議? – Metaphysiker

+0

@Metaphysiker你添加代碼到你的預覽,而不是郵件本身,預覽應該返回一個郵件對象 – Vasfed

+0

我是個白癡。謝謝! – Metaphysiker

1

@infosall應是被一起模板傳遞ExampleMailer的實例變量,但你不設置在郵件這個變量。您需要將其設置在您ExampleMailer你sample_email方法,以便它在你的模板中的任何值或意義。

+0

我加入sample_email的東西,但我得到一個錯誤(見我的編輯),有何意見? – Metaphysiker

+0

您將其添加到'sample_email_preview',而不是'sample_email'。至於你提到的錯誤,它是在你甚至沒有從任何發佈的代碼中調用的方法中,所以我不確定它與OP的關係。 –

+0

是的,Vasfed也指出了這一點。我是個白癡。謝謝! – Metaphysiker