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