This should be a very basic question, I’m still new to ruby so i’d appreciate some help.
So I have 3 tables in my db, Source, SourceType and Feed. Every Source belongs to a SourceType and Every Feed Belongs to a Source. Their primary keys are SourceID, TypeID and FeedID
my Active Record Classes are:
class SourceFeed < ActiveRecord::Base
self.table_name = "SourceFeed"
self.primary_key = "FeedID"
belongs_to :Source,
:foreign_key => "SourceID",
:class_name => "Source",
:include => "SourceType"
end
class Source < ActiveRecord::Base
self.table_name = "Source"
self.primary_key = "SourceID"
has_many :SourceFeeds,
:primary_key => "SourceID",
:class_name => "SourceFeed"
belongs_to :SourceType,
:foreign_key => "TypeID",
:class_name => "SourceType"
end
class SourceType < ActiveRecord::Base
self.table_name = "SourceType"
self.primary_key = "TypeID"
has_many :Source,
:primary_key => "TypeID",
:class_name => "Source"
end
I am trying to select stuff from SourceFeed, Stuff from Source and the SourceType. Here’s the query:
feed = SourceFeed.select("SourceFeed.FeedID, Source.Name as SourceName, SourceType.Name as SourceType").joins(:Source, :SourceType).where(:FeedID => FeedID).first
I am getting a Association named 'SourceType' was not found; perhaps you misspelled it? Error
If I remove it from the Joins, I get an Unknown column 'SourceType.Name' in 'field list' error.
What’s the right way to do it?
Thanks
PS: My database doesn’t follow active records naming conventions, but I can’t change that I am working with an existing DB.
Your query only works if there’s an association named “SourceType” defined in SourceFeed. You don’t have it, so you got the error.
I think this should work:
UPDATE:
Definitely, Derek Harmel’s answer is a better one. SQL should be avoided whenever possible.