N:M find confusion

Hello!

I have an N:M mapping of tables. There are three tables involved:

constraints
id
name

people
id
first_name
last_name

constraints_people
constraint_id
person_id

Here is some Ruby code that I have created in order to make the
mapping:

class Person < ActiveRecode::Base
has_and_belongs_to_many: constraints, :class_name => “Constraint”
end

class Constraint < ActiveRecod::Base
has_and_belongs_to_many: people, :class_name => “Person”
end

I would now like to get an array of people who have a constraint id of
e.g. 1. I don’t know how to get this result, I have now tried the
following:

sql_result = Person.find_by_sql("select person_id from
constraints_people where constraint_id = " + constraint.id.to_s)
@people = Person.find(sql_result)

But the sql_result is an assocative array and I only want the IDs. Is
it the correct way to do this with find_by_sql() or is there a better
way to get the @people filled?

Thanks!
Christoph

Hi Cristoph.

Having defined the habtm relationship between Constraints and People,
you have several methods to navigate through them. In particular, you
have a people method in the Contraint class, so you can do

contraint.people

to get the people associated to constraint. To go the other way and find
the constraints for a given person

person.constraints

So, to get the people associated to constraint with ID 1 you just need
to find the constraint by the id and ask it for its people

Constraint.find(1).people

In general, you wouldn’t use find_by_sql but in special cases.

By the way, since you have named both tables (plural) and classes
(singular) according to Ror standars you don’t need to specify the
:class_name param in the habtm declarations, you have the default.

Regards

[email protected] escribi�:

first_name
has_and_belongs_to_many: constraints, :class_name => “Constraint”
sql_result = Person.find_by_sql("select person_id from


Andr�s Cirugeda E.
ASPgems
Email: andres at aspgems dot com

‘All we have to decide is what to do with the time that is given to us’.
Gandalf.

Ouch… hurts to see the beginners use find_by_sql and such. Poor
php/java developers aren’t used to the beauty of ruby =(

Read the beginners guides here: http://wiki.rubyonrails.com/rails

[email protected] wrote:

first_name
has_and_belongs_to_many: constraints, :class_name => “Constraint”
sql_result = Person.find_by_sql("select person_id from
constraints_people where constraint_id = " + constraint.id.to_s)
@people = Person.find(sql_result)

But the sql_result is an assocative array and I only want the IDs. Is
it the correct way to do this with find_by_sql() or is there a better
way to get the @people filled?

All you need is

@people = constraint.people

given that you’ve found constraint using something like

constraint = Constraint.find(1)


We develop, watch us RoR, in numbers too big to ignore.