undefined method `new_record?' for nil:NilClass-Collection of common programming errors
In rails 3.2 I created a post controller. Each post can have a different number of paperclip attachments. To achieve this I created a assets model where each asset has a paperclip attachment. One post has_many assets and assets belong_to post.
Asset model
class Asset < ActiveRecord::Base
belongs_to :post
has_attached_file :photo, :styles => { :thumb => "200x200>" }
end
Post model
class Post < ActiveRecord::Base
attr_accessible :content, :title
has_many :assets, :dependent => :destroy
validates_associated :assets
after_update :save_assets
def new_asset_attributes=(asset_attributes)
asset_attributes.each do |attributes|
assets.build(attributes)
end
end
def existing_asset_attributes=(asset_attributes)
assets.reject(&:new_record?).each do |asset|
attributes = asset_attributes[asset.id.to_s]
if attributes
asset.attributes = attributes
else
asset.delete(asset)
end
end
end
def save_assets
assets.each do |asset|
asset.save(false)
end
end
end
Posts helper
module PostsHelper
def add_asset_link(name)
link_to_function name do |post|
post.insert_html :bottom, :assets, :partial => 'asset', :object => Asset.new
end
end
end
Form for post
{ :multipart => true } do |f| %>
prohibited this post from being saved:
Attach a file or image
@post.assets %>
Asset partial
Asset:
Most of the code is taken from here: https://gist.github.com/33011 and I understand this is a rails2 app, anyway I don’t understand what this error means:
undefined method `new_record?' for nil:NilClass
Extracted source (around line #2):
1:
2:
3:
4:
5:
-
Try changing this
Attach a file or image
@post.assets %>to
Attach a file or image
asset %>Possible reason is when u calling
@post.assets %>
You are passing a collection to the rendered partial but you are no where using ur collection passed by the name collection in the partial. you are using a variable Assest which doesnt exist in scope of that particular rendered partial 🙂
-
Reading the error, your
@post.assets %>
line calls an empty array maybe? In your console, can you find @post.assets and is it nil there?
Originally posted 2013-11-09 21:05:57.