Newbie: access model inside a model


#1

Hi everybody,

I’ve started to learn Ruby on Rails with the two books, of course I’m
experimenting outside
the examples in the book and walking against some things I didn’t learn
yet. so here’s the question:

Is it possible to access one model from within another? Actually I have
a Many to Many relationship
between tables and I’m trying to realize this without
“has_and_belongs_to_many”.

Maybe someone can push me in the right direction.

Kind regards,
Jeroen van Doorn


#2

Jeroen van Doorn wrote:

a Many to Many relationship
between tables and I’m trying to realize this without
“has_and_belongs_to_many”.

Why do you want to avoid has_and_belongs_to_many? It’s going to make
things a lot easier for you.

But the answer to your question is yes, there’s nothing preventing one
model from talking to another. Each class that derives from
ActiveRecord::Base gets a slew of class methods that can be called both
internally and externally, like find() and find_by_sql().

Look at find(:first) and find(:all) to get started. For example,

class Hockey < ActiveRecord::Base

end

class Baseball < ActiveRecord::Base

def hello
Hockey.find(:first, :conditions => “team_id = 10”)
end

end

b = Baseball.new
b.hello # will find a hockey team

But still, you really should learn about has_and_belongs_to_many in most
cases.

Jeff
www.softiesonrails.com


#3

Jeff C. wrote:

But the answer to your question is yes, there’s nothing preventing one
class Baseball < ActiveRecord::Base
But still, you really should learn about has_and_belongs_to_many in most
cases.

Jeff
www.softiesonrails.com

Hi Jeff,

I really don’t have a good reason to avoid it, just trying to learn and
understand!
Wil use has_and_belongs_to_many in the future.

Thanks for the help,
Jeroen