I have two models:
class Thread < ActiveRecord::Base
has_many :attachments
end
class Attachment < ActiveRecord::Base
belongs_to :thread
end
When creating a new thread I want to build attachments before saving. I’m doing:
@thread.attachments.build(...)
but that is erroring with: failed with NoMethodError: undefined method `build' for #<Class:0x10338c828
You should be able to use
@thread.attachments.buildto create a new unsaved attachment.If you have
:autosave => trueon yourhas_many(either explicitly or viaaccepts_nested_attributes_for) they will be saved when the parent thread saves.You may need to set
:inverse_ofon the associations for saving of new records to work correctly:As mentioned by @zetetic:
Threadis a built in Ruby class and you should not use the same name as a system class in your app.There are a number of classes in any language which you learn to not use. In such cases I would add something to my classname to make it more descriptive, assuming there’s not a better name altogether. Taking a stab at what you app is, you should rename this from
Threadto something likeMessageorMessageThread.What’s happening is that as
Threadis a core class that is loaded before your app code. There’s already aThreadclass in memory and Rails does not go looking for it in development mode when you first reference it. Rails loads your classes on demand in development by looking for athread.rbfile whenThreadis referenced and not currently loaded.In production mode, Rails loads all classes at startup and the differing base class (
ObjectvsActiveRecord::Base) will result in aTypeError.