I am relatively new to rails and think that my problem may, in part, be due to me lacking a clear understanding of the nature and Scope of Ruby’s Classes and the objects that they produce.
I am getting the following error:
Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
Rails.root: /Users/rmcnairn/rails/search
Application Trace | Framework Trace | Full Trace
app/models/photo.rb:17:in `scanner'
app/controllers/suppliers_controller.rb:66:in `block in update'
app/controllers/suppliers_controller.rb:65:in `update'
After Creation of a Photo record. I would like to use that new record to reference an associated record (a Fabric), and call an instance method (Scan) on that record.
Scan is defined in the Fabric Class.
My records are setup so that
a Photo *has_many* Fabrics :through Fabric_Photos
This is a snapshot of my Photo Class and my attempt to find this association and call the scan method on it.
class Photo < ActiveRecord::Base
has_many :fabrics, :through => :fabric_photos
has_many :fabric_photos
after_create :scanner
accepts_nested_attributes_for :fabrics
mount_uploader :image, ImageUploader
def scanner
if self.fabric == true #fabric is a boolean column in the Photo table
self.fabrics.first.scan
else
return
end
end
end
EDIT
I Have added the Relevant Supplier Controller code
Suppliers have_many fabrics, fabrics have many photos
def update
@supplier = Supplier.find(params[:id])
respond_to do |format| # line 65
if @supplier.update_attributes(params[:supplier])
format.html { redirect_to suppliers_url, notice: @supplier.name.to_s + ' was updated' }
format.json { head :no_content }
else
format.html { render action: "edit", notice: @supplier.name.to_s + ' was NOT updated' }
format.json { render json: @supplier.errors, status: :unprocessable_entity }
end
end
end
Would it be possible for you to help me understand a little more about the nature of the associated object that I am calling and the limitations, if any that are placed on calling methods on it in another class.
I presume that
self.fabrics.first
Is returning something that is incapable of having the method .scan called on it. It would be great is someone would explain to me what Active Record is actually producing here.
Many thanks
The issue is that
self.fabrics.firstis returning nil. In the underlying database, this means the sql query generated by Rails returned null.I would look at the controller code, or whatever you used to create the models. You may not be saving/updating the related models to connect everything. Also, take a look at each table and the id’s of the records there to see for yourself what is and isn’t being created.
In the database, you should see that if you run the sql code rails generates (look in the log), that in the fabrics table you don’t have something that meets the query criteria.