Assuming the following model:
class Section < ActiveRecord::Base
belongs_to :teacher
has_many :students
end
class Teacher < ActiveRecord::Base
has_many :sections
has_many :students, :through => :sections
end
class Student < ActiveRecord::Base
belongs_to :section
has_one :teacher, :through => :section
end
When I try to access student.teacher, I get the error:
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column:
sections.section_id: SELECT “teachers”.* FROM “teachers” INNER JOIN
sections ON teachers.id = sections.teacher_id WHERE
((“sections”.section_id = 1))
Does anyone have any idea why it’s looking for sections.section_id
instead of sections.id?
It’s funny because I just had the same problem in my project.
It seems I was applying the has_to and the belongs_to on reverse.
Allow me to explain: I had two classes called Ad and TenureCategory
like this
class Ad < ActiveRecord::Base
has_one :TenureCategory
end
class TenureCategory < ActiveRecord::Base
belongs_to :Ad
end
when I tried to use these associations like
Ads.find(:first).TenureCategory I also got an SQL error stating that
either a column couldn’t be found or an entire table. It seems like I
got it wrong from the begining and, in fact, it’s more appropiate to
think that a TenureCategory has many Ads instead so I changed it like
so:
class Ad < ActiveRecord::Base
belongs_to :TenureCategory, :foreign_key => ‘id’
end
class TenureCategory < ActiveRecord::Base
has_many :Ads
end
and now it works perfectly!
Perhaps in your case you should change the relationships about your
models or specify a foreign key to join them.
Hope I was of help
Relationship names must be plural? How do you figure? If B
belongs_to A, you’d never say “B belongs to As.” It’s semantically
confusing if that’s the case. I tried this with no luck.
Relationship names must be name of the table, which is plural.
Http://www.rubyplus.org
Free Ruby & Rails screencasts
On 9 Jun 2008, at 05:48, Doug Mayer wrote:
Relationship names must be plural? How do you figure? If B
belongs_to A, you’d never say “B belongs to As.” It’s semantically
confusing if that’s the case. I tried this with no luck.
Nope it’s just wrong. has_one and belongs_to are singular by
convention (although the name of an association can be anything you
want, following the convention just saves you from having to specify
the class and foreign key explicitly
Fred
Yep, I’m running the released version of 2.1.0.
Does anyone have any idea why it’s looking for sections.section_id
instead of sections.id?
has_one didn’t support :through until Rails 2.1. Are you running 2.1?