有_许多& belongs_to 不在 Rails 中工作
我在 Rails 应用程序中创建了两个模型 1) Contact 2) Customer,现在我想连接这些模型的两个表。表是联系人和联系人分别为客户。我正在使用以下代码:
1)contact.rb:
class Contact < ActiveRecord::Base
unloadable
has_many :customers
end
2)customer.rb
class Customer < ActiveRecord::Base
belongs_to :contact, :foreign_key => :contact_id`
end
3)customers_controller.rb
def new
@customer = Customer.new
@customer = Customer.find(:all,:include => :contact_id)
end
这里我试图将联系人表的主键访问到客户表中,但它反复给出此错误“名为“contact_id”的关联是没找到;也许你拼错了?”有人可以帮我解决这个问题吗?
I have created two models 1) Contact 2) Customer in my Rails application, now I want to join the two tables of these models. Tables are contacts & customers respectively. I am using following code:
1) contact.rb:
class Contact < ActiveRecord::Base
unloadable
has_many :customers
end
2) customer.rb
class Customer < ActiveRecord::Base
belongs_to :contact, :foreign_key => :contact_id`
end
3) customers_controller.rb
def new
@customer = Customer.new
@customer = Customer.find(:all,:include => :contact_id)
end
Here I am trying to access the primary key of contact table into customer table but it repeatedly gives this error "Association named 'contact_id' was not found; perhaps you misspelled it?" Can any one help me on this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您使用
include
时,您应该传入关联名称(在您的例子中为“contact
”)而不是外键。但是,您的描述并没有明确表明这就是您想要做的,所以如果您能澄清您的问题,如果它是错误的,我会更新这个答案
When you use
include
, you should pass in the association name (in your case "contact
") rather than the foreign key.However, your description doesn't make clear that this is what you want to do, so if you can clarify your question I'll update this answer if it's wrong
如果我清楚地理解您不需要在联系人模型中将客户复数:
并且您不需要指定包含外键的列的名称
(对不起我的英语)
If I clearly understand you don't need to pluralize customer in the contact model :
And you don't need to specified the name of the column who contain the foreign key
(sorry for my english)