2012-03-07 104 views
0

这是我第一次创建has_and_belongs_to_many关联,并且它不太合作。无法获得has_and_belongs_to_many关联创建

我的模型

class Server < ActiveRecord::Base 
    has_and_belongs_to_many :services 

class Service < ActiveRecord::Base 
    has_and_belongs_to_many :services 

我试图通过创建服务器对象的服务。

我已经得到了服务器对象server = Server.find_by_name(server_name),它工作得很好。如果我尝试创建一个服务对象,无论是service = server.services.newserver.services.create(params)我得到以下的ActiveRecord错误:

ActiveRecord::HasAndBelongsToManyAssociationForeignKeyNeeded: Cannot create self referential has_and_belongs_to_many association on 'Service#services'. :association_foreign_key cannot be the same as the :foreign_key. 

我还没有发现在该错误信息的方式很多,但。我究竟做错了什么?

回答

2

简单的错误:

应该是您的服务类has_and_belongs_to_many :servers

+0

gah,感谢您排查我的错字。 – Eugene 2012-03-07 17:18:22

0

第一,我认为你有一个错字有你的意思是服务器没有服务

它必须是

class Service < ActiveRecord::Base 
    has_and_belongs_to_many :servers 

有两种方式安装许多-to-many关联插件的轨道,我会建议使用has_many:因为has_and_belongs_to_many非常有限。

Ryan在这个主题上创建了一个很好的Railscasts,这非常有帮助! http://railscasts.com/episodes/47-two-many-to-many

相关问题