0

Hi I am using Rails 4rc1. Really cant figure it out, why @feed.id isnt recognized in my feeds.js file. Thx for help.

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

Application Trace:

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'

daniel
  • 3,105
  • 4
  • 39
  • 48
  • 1
    Are you compiling the is on the fly or is it precompiled? Also, I'm not sure that the asset pipeline has access to the controller instance, never tried to do that. – cpuguy83 May 28 '13 at 23:34
  • Hi cpuguy! Its only on localhost. I didnt run any rake:assets:precompile – daniel May 29 '13 at 00:10
  • 1
    Make sure `@feed` is not nil. Do you have any `Feed`s in your database? – Soliah May 29 '13 at 00:50

1 Answers1

1

As a rule of thumb I never return scripts as ajax responses. Instead I return json objects. That way javascript can just inspect the json and get the correct id in your case for the fadeOut. Your better off doing this. It's also keeps your application more restful and allows you to keep your JS in assets. In your case your loading a script from assets that is not aware of any ivars in your controller. This is why your getting a your error. @feed is never set in this scope.

Stewart
  • 3,023
  • 2
  • 24
  • 40