Reputation: 749
I am a newbie in the Rails framework. 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.
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?
Upvotes: -1
Views: 444
Reputation: 20046
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 %>
Upvotes: 1
Reputation: 168071
You have class DealersGroup
whereas you are looking for dealer_group_id
.
Upvotes: 0