开发者

rails foreign key problem

开发者 https://www.devze.com 2023-03-06 05:09 出处:网络
I am a newbie in the Rails framework. I\'ve created tables: DealerGroups开发者_JS百科Dealer ------------------------

I am a newbie in the Rails framework. I've created tables:

DealerGroups                      开发者_JS百科   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.

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.

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

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 %>


You have class DealersGroup whereas you are looking for dealer_group_id.

0

精彩评论

暂无评论...
验证码 换一张
取 消