开发者

Rails 3 - Using build -error, undefined method `build' for #<Class:0x10338c828

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:0x10338c82开发者_如何学JAVA8


You should be able to use @thread.attachments.build to create a new unsaved attachment.

If you have :autosave => true on your has_many (either explicitly or via accepts_nested_attributes_for) they will be saved when the parent thread saves.

You may need to set :inverse_of on the associations for saving of new records to work correctly:

class Thread < ActiveRecord::Base
  has_many :attachments, :inverse_of => :thread, :autosave => true
end

class Attachment < ActiveRecord::Base
  belongs_to :thread, :inverse_of => :attachments
end

As mentioned by @zetetic: Thread is 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 Thread to something like Message or MessageThread.

What's happening is that as Thread is a core class that is loaded before your app code. There's already a Thread class 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 a thread.rb file when Thread is referenced and not currently loaded.

In production mode, Rails loads all classes at startup and the differing base class (Object vs ActiveRecord::Base) will result in a TypeError.


Thread is a reserved word in Ruby -- I'd suggest renaming your model.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜