我是不是漏掉了什么?
话语模式:
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
endDiscourseReply模型:
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是一个未定义的方法?
发布于 2014-04-04 23:43:55
您已经为has_many定义了discourse_replies关联,因此要创建需要执行的关联对象
fd.discourse_replies.create如果您将fd.create_discourse_reply与has_one或belongs_to关联关联起来,那么它将被创建为对象。
https://stackoverflow.com/questions/22874733
复制相似问题