Distinct?

This should be easy, but I’m stumped…

class X < ActiveRecord::Base
belongs_to :y
end
class Y < ActiveRecord::Base
has_many :x
end

The y table has a column names. The x table has a column value. I
want the list of values in x for the name “Location” in y. Yes, there
are many repetitions.

I can probably hack together an SQL statement to do this without too
much trouble, but the point of using rails is kinda to avoid that when
we can, right?

Student

Hi, if you would like to obtain the x collection of y, you simply need
to do
the following:

renaming y to teacher

renaming x to student

Now, we can say the following:

a_teacher.students

Good luck,

-Conrad

No, I’m looking for the names of the teachers who teach fifth grade.

No, I’m looking for the names of all of the teachers who are teaching
students that are in the fifth grade. (The students are in the fifth
grade.)

No, I’m looking for the first names of the students of the band
teachers.

On 9/17/07, Student [email protected] wrote:

The y table has a column names. The x table has a column value. I
want the list of values in x for the name “Location” in y. Yes, there
are many repetitions.

You first find the Y row for “Location”:

row = Y.find_by_names(‘Location’)

That returns nil if there is no such row. If there are multiple rows,
it returns only the first. If you want all matches, you need to use

rows = Y.find_all_by_names(‘Location’)

Then all the associated X rows can be found via the “x” method of the Y
object:

results = row.x.collect :&value

(n.b. the normal convention is to use the plural form in has_many;
i.e. “has_many :xs”)

On 9/18/07, Student [email protected] wrote:

No, I’m looking for the first names of the students of the band
teachers.

That doesn’t match your original description of the problem.

Why not give us the actual models, columns, etc. It’s hard to think in
terms of x’s and y’s.

So I see.

class Subprojectattr < ActiveRecord::Base
belongs_to :attribute
end
class Attribute < ActiveRecord::Base
has_many :subprojectattrs
end

So I want the list of Subprojectattr.valueStrs when spa.attribute.name
== “Location”. Yes, this is a legacy database, so I cannot fix the
organizational problems via schema changes.

Student

BTW, I get the results I want with the following sql:

SELECT dbo.subProjectAttr.valueStr
FROM dbo.subProjectAttr INNER JOIN
dbo.attribute ON dbo.subProjectAttr.attributeId
= dbo.attribute.attributeId
WHERE (dbo.attribute.name = ‘Location’)
GROUP BY dbo.subProjectAttr.valueStr

As I said, however, the idea is to avoid having to put this stuff in
directly.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs