データベース内のすべてのチャンセラーのすべての名前を読み取り、この値を HAML テンプレートに渡そうとする rake タスクを作成しています。
より効率的にするために、コレクション オプションを使用してテンプレートをレンダリングしました (以下のソース コードを参照)。しかし、そのタスクを実行しようとすると、常に次のエラー メッセージが表示されます。
undefined local variable or method `name' for #<Template:0x007f9094286078>
この問題のタスク コードは次のとおりです。
task :template => :environment do
#this class is responsible for rendering templates in a rake task
class Template < ActionView::Base
include Rails.application.routes.url_helpers
include ActionView::Helpers::TagHelper
def default_url_options
{host: 'yourhost.org'}
end
end
firstNames = Array.new
#stores the first names of all chancellors in an array
for chans in Chancellor.all
firstNames.push(chans.first_name)
end
#sets the path to the template
template = Template.new(Rails.root.join('lib','tasks'))
#trying to render the template with a collection
finalString = template.render(:template => "_chancellor.xml.haml",
:collection => firstNames, :as => :name)
puts finalString
end
そして、入力する必要がある haml テンプレートは次のとおりです。
%firstname #{name}
次のような出力を取得したい:
<firstname>someName1</firstname>
<firstname>someName2</firstname>
<firstname>someName3</firstname> ....
次のようになるように、名前をインスタンス変数としてテンプレートに入れてみました。
%firstname #{@name}
しかし、 firstname の値は空で、次の行を出力として取得します。
<firstname></firstname>
構文エラーの原因は何ですか?