Terrytreks
Terrytreks

Reputation: 266

Association not creating methods

I have User, Guide, and CityObj models. User has one Guide, and Guide belongs to User. This allows me to use methods to access the parent from the child and vice versa:

a_user.guide
a_guide.user

But these methods aren't there for CityObj:

a_guide.cityobj ----> error
a_cityobj.guide ----> error

Maybe it has to do with the camel case? It seems like I'm doing the same thing for User/Guide and Guide/CityObj.

User.rb

class User < ActiveRecord::Base

  has_one :guide, dependent: :destroy

  ...

end

Guide.rb

class Guide < ActiveRecord::Base
  has_one :cityObj, dependent: :destroy
  belongs_to :user

  ...
end

CityObj.rb

class CityObj < ActiveRecord::Base
  belongs_to :guide
end

Upvotes: 0

Views: 25

Answers (2)

charlysisto
charlysisto

Reputation: 3700

As @Pavan said the convention should be snake case, including for the filenames and the association definition (and methods in general)

  • CitObj.rb should be city_obj.rb
  • User.rb should be user.rb

Also :

class Guide < ActiveRecord::Base
  has_one :city_obj, dependent: :destroy
  belongs_to :user

  # ...
end

This will "generate" association methods like : build_city_obj etc...

Upvotes: 0

Pavan
Pavan

Reputation: 33542

As per convention, you should use snake case

a_guide.cityobj
a_cityobj.guide

should be

a_guide.city_obj
a_city_obj.guide

Also, change your association in guide.rb model to below.

#guide.rb
has_one :city_obj, dependent: :destroy

Upvotes: 1

Related Questions