[英]Controller for Mailer in Ruby on Rails, Active Record query
我遵循了為在Rails上設置紅寶石郵件的指南(該指南的站點: https : //launchschool.com/blog/handling-emails-in-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
我哪里做錯了? 有什么建議嗎?
@infosall
應該是ExampleMailer的實例變量,該實例變量將傳遞給模板,但是您未在郵件程序中設置此變量。 您需要在ExampleMailer的sample_email
方法中進行設置,以使其在模板中具有任何值或含義。
郵件程序與控制器無關。 同樣,為某個模型定義show
action時,使用該模型渲染某些東西時不會調用它。
將郵件程序視為控制器,在其操作中設置所有需要的實例變量(在這種情況下為sample_email
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.