实例变量未传递给Rails 4 rc1中的资产js文件

时间:2013-05-28 23:17:51

标签: ruby-on-rails sprockets

您好我正在使用Rails 4rc1。真的无法弄清楚,为什么@feed.id在我的feeds.js文件中无法识别。求助。

NoMethodError in Feeds#index
Showing myapp/app/views/layouts/application.haml where line #6 raised:

undefined method `id' for nil:NilClass
(in myapp/app/assets/javascripts/feeds.js.coffee.erb)

#application.haml

%head
  %title Rails4Bootstrap
  = stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true
  = javascript_include_tag "application", "data-turbolinks-track" => true
  = csrf_meta_tags
%body

#feeds_controller.rb

def index
@feeds = Feed.all
@feed = Feed.new

respond_to do |format|
  format.html # show.html.erb
  format.json { render json: @feeds }
  format.js
end
end

def destroy
  @feed = Feed.find(params[:id])
  @feed.destroy
  respond_to do |format|
    format.html { redirect_to feeds_path, notice: "Feed successfully deleted." }
    format.json { head :no_content }
    format.js
  end
end

#views / feeds / index.haml

= form_for(@feed, remote: true) do |f|
  .field
    = f.label :url
    %br/
    = f.text_field :url
  .actions
    = f.submit


- @feeds.each do |feed|
  #feed{"data-id" => feed.id}
  ....
    = link_to 'Delete', feed, method: :delete, remote: true

#assets / javascripts / feeds.js.coffee.erb

$('#feed_<%= @feed.id %>').fadeOut

应用程序跟踪:

app/assets/javascripts/feeds.js.coffee.erb:27:in `block in singleton class' app/assets/javascripts/feeds.js.coffee.erb:-5:in `instance_eval' app/assets/javascripts/feeds.js.coffee.erb:-5:in `singleton class' app/assets/javascripts/feeds.js.coffee.erb:-7:in `__tilt_70104733785500' app/views/layouts/application.haml:6:in `_app_views_layouts_application_haml__4512126609701308533_70104706177220' app/controllers/feeds_controller.rb:28:in `index'

1 个答案:

答案 0 :(得分:1)

根据经验,我永远不会将脚本作为ajax响应返回。相反,我返回json对象。这样javascript就可以检查json并在你的情况下为fadeOut获取正确的id。你最好这样做。它还可以使您的应用程序更加安静,并允许您将JS保留在资产中。在您的情况下,您从不知道控制器中的任何ivars的资产加载脚本。这就是你得到错误的原因。 @feed永远不会在此范围内设置。