我正在尝试从像这样的rake任务中访问名为Book
的模型
task :create_epubs => :environment do
include Rails.application.routes.url_helpers # brings ActionDispatch::Routing::UrlFor
include ActionView::Helpers::TagHelper
av = ActionView::Base.new(Rails.root.join('app', 'views'))
books = Book.all
av.render("books/", :books => books)
end
但我收到以下警告
rake aborted!
undefined method `to_sym' for nil:NilClass
Tasks: TOP => create_epubs
(See full trace by running task with --trace)
我正在尝试像下面的accessing rails models from rake task那样加载环境但是对于rails 3.1来说可能稍微偏离了
*编辑Book.all会在我放入Book.all.to_yaml时返回一些内容,因此to_sym错误可能是av.render中的其他内容
我已经弄明白了问题所在。我在我看来是指实例变量。
有人能告诉我如何通过设置该变量继续使用实例变量吗?
当我将实例变量更改为:params变量
时,这是工作版本task :create_epubs => [:environment] do
av = ActionView::Base.new(Rails.root.join('app', 'views'), :assigns => self)
av.view_paths = ActionController::Base.view_paths
av.extend ApplicationHelper #or any other helpers your template may need
book = Book.first
puts av.render(:template => "books/epub-show", :locals => {:book => book}, :layout => false) # this isn't passing @book to the view correctly, i get undefined method for nil:nilClass
end
答案 0 :(得分:0)
你应该使用实例变量。
@book = Book.first
并在你的渲染中
:locals => { :book => @book }
另外,我想你想要
:layout => nil