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?
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”)
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.
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.