[英]Rake task to access models
我正在嘗試從這樣的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)
我正在嘗試從rake任務中加載如下所示的環境以訪問Rails模型,但對於Rails 3.1可能略有下降
* edit當我將Book.all.to_yaml放入Book.all時會返回某些內容,因此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
您可能應該使用實例變量。
@book = Book.first
並在您的渲染中
:locals => { :book => @book }
另外,我想你想要
:layout => nil
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.