Has_many and belongs_to in rails 2.0.2 (child.Parent) is not working

Hi All

I have 2 models working well in rails 1.2.6 :

class TypeService < ActiveRecord::Base
has_many :Services
end

class Service < ActiveRecord::Base
belongs_to :TypeService
end

I was able to get the name of the service with Rails 1.2.3:

s = Service.find(1)
name_type_service = s.TypeService.name <<-- Now with rails 2.0.2
that doesn’t work

With rails 2.0.2

s = Service.find(1)
s.TypeService.name
nil <<-- TypeService is nil with rails 2.0.2

Does any one know why that “child.parent” is not working with rails
2.0.2 anymore?

Thank you very much for your help

On 22 Feb 2008, at 15:53, hhvm wrote:

belongs_to :TypeService
end

The expected names would be has_many :services and
belongs_to :type_service. It’s possible that 2.0 is enforcing this
more strictly.

Fred.

Thank you very much but I just changed that, and No, that is still
not working.

I’m not sure why I’m not able to get the Parent class in rails 1.2.3
that was working well.

parent = child.Parent <<-- that was i
nil <<-- nil with rails 2.0.2

On Feb 22, 10:58 am, Frederick C. [email protected]

hhvm wrote:

parent = child.Parent <<-- that was i
nil <<-- nil with rails 2.0.2

It depends on the definition of your services table. The standard way
is for the services table to contain a column called type_service_id and
then use:

class TypeService < ActiveRecord::Base
has_many :services
end

class Service < ActiveRecord::Base
belongs_to :type_service
end

s = Service.find(1)
name_type_service = s.type_service.name

The arguments to “has_many” and “belongs_to” become methods in the class
which return the connected object(s) from the other class. The
“belongs_to” method returns a single object and the “has_many” method
returns an array of objects, so similarly:

t = TypeService.find(1)
services_for_t = t.services

Here services_for_t is now a (possibly empty) array of Service objects.

If the column in your services table is called something else, then you
need to specify it as the foreign key in the relation, so if this column
is typeservice_id, for example, use:

class TypeService < ActiveRecord::Base
has_many :services, :foreign_key => :typeservice_id
end

class Service < ActiveRecord::Base
belongs_to :type_service, :foreign_key => :typeservice_id
end

Thank you very much,

I got it I was using TypeService
like :

belongs_to :TypeService

I change it to

belongs_to :type_service

now that is working,

Thank you Mark for your help.

Regards

On Feb 22, 2:05 pm, Mark B. [email protected]