通过自引用关联创建实例

时间:2014-04-04 23:37:03

标签: ruby-on-rails activerecord

我在这里错过了什么吗?

话语模型:

class Discourse < ActiveRecord::Base        
    #<Discourse id:, user_id: , sub_discourse_id: , title: , body: , deleted: , delete_date: , created_at:, updated_at: >   
    has_many :discourse_replies
    has_many :replies, through: :discourse_replies 
end

DiscourseReply模型:

class DiscourseReply < ActiveRecord::Base
    belongs_to :discourse
    belongs_to :reply, class_name: 'Discourse' 
end

控制台:

Loading development environment (Rails 4.0.2)
2.0.0p247 :001 > fd = Discourse.create(title: 'first', body: 'first')
 => #<Discourse id: 5, user_id: nil, sub_discourse_id: nil, title: "first", body: "first", deleted: nil, delete_date: nil, created_at: "2014-04-04 23:32:13", updated_at: "2014-04-04 23:32:13"> 
2.0.0p247 :002 > fd.discourse_replies
 => #<ActiveRecord::Associations::CollectionProxy []> 
2.0.0p247 :004 > fd.create_discourse_reply
NoMethodError: undefined method 'create_discourse_reply' for #<Discourse:0x00000003396450>
2.0.0p247 :004 > fd.discourse_replies.build(title: "reply to first", body: "reply to first")
ActiveRecord::UnknownAttributeError: unknown attribute: title

简而言之,为什么create_discourse_reply是未定义的方法?

1 个答案:

答案 0 :(得分:1)

您已为discourse_replies定义了has_many关联,以便创建您需要执行的关联对象

fd.discourse_replies.create
如果您已将对象与fd.create_discourse_replyhas_one关联相关联,则

belongs_to会被创建。