简体   繁体   English

Rails外键问题

[英]rails foreign key problem

I am a newbie in the Rails framework. 我是Rails框架的新手。 I've created tables: 我已经创建了表格:

DealerGroups                         Dealer 
------------                         ------------
Id:integer(primary key)              Id:integer(primary key)
name:string                          dealer_group_id:integer(foreign key)

But when I try to set Dealer.dealer_group_id = value (this value exists in the DealerGroups table) I get an "UninitializedConstant Dealer::DealerGroup" exception. 但是,当我尝试设置Dealer.dealer_group_id = value (此值存在于DealerGroups表中)时,出现“ UninitializedConstant Dealer :: DealerGroup”异常。

In models I have : 在模型中,我有:

class Dealer < ActiveRecord::Base
  belongs_to :dealer_buying_group, :foreign_key => "dealer_buying_group"
end

class DealersGroup < ActiveRecord::Base
  has_many :dealer
end

If I delete the has_many and belongs_to relations, it all works fine. 如果删除has_manybelongs_to关系,则一切正常。

Why won't it work with the relations? 为什么对这种关系不起作用?

Be careful with the "s" (why is your "Dealer" table is not "Dealers"?) You do not need to manually set a foreign key in Rails, all you need to define the Model_ID field to it as you generate your scaffold/model/controller, then belongs_to and has_many in the model will do the relation for you 注意“ s”(为什么您的“ Dealer”表不是“ Dealers”?)您不需要在Rails中手动设置外键,在生成支架时只需为其定义Model_ID字段即可。 / model / controller,然后模型中的belongs_tohas_many将为您建立关系

Database: 数据库:

DealerGroups                         Dealers 
------------                         ------------
Id:integer(primary key)              Id:integer(primary key)
name:string                          dealergroup_id:integer

Models : 型号

class Dealer < ActiveRecord::Base
  belongs_to :dealergroup
end

class DealersGroup < ActiveRecord::Base
  has_many :dealers
end

To access dealdergroup's name from dealers, just use 要从经销商处访问交易者组的名称,只需使用

controller: 
@dealer = Dealer.find_by_id(myInt)

view:
<%= @dealer.dealergroup.name %>

您有DealersGroup类,而您正在寻找dealer_group_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM