Let's say we have 3 models:
class Group < ActiveRecord::Base
has_many :resources
has_many :users
end
class Resource < ActiveRecord::Base
belongs_to :group
end
class User < ActiveRecord::Base
belongs_to :group
has_many :resources, :through => :group
end
We want to access the resources of the group from the User model. When we try to access the resources association, Rails will reoprt an SQL error:
>> User.find(1).resources
User.find(1).resources
ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'groups.group_id' in 'where clause': SELECT resources.* FROM resources INNER JOIN groups ON resources.group_id = groups.id WHERE ((groups.group_id = 1))
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record/connection_adapters/abstract_adapter.rb:150:in `log'
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record/connection_adapters/mysql_adapter.rb:281:in `execute'
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record/connection_adapters/mysql_adapter.rb:481:in `select'
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record/connection_adapters/abstract/database_statements.rb:7:in `select_all_without_query_cache'
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record/connection_adapters/abstract/query_cache.rb:55:in `select_all'
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record/base.rb:532:in `find_by_sql'
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record/base.rb:1233:in `find_every'
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record/base.rb:503:in `find'
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record/associations/has_many_through_association.rb:140:in `find_target'
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record/associations/association_proxy.rb:133:in `load_target'
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record/associations/association_proxy.rb:55:in `reload'
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record/associations/association_proxy.rb:77:in `inspect'
from /usr/lib/ruby/1.8/irb.rb:298:in `output_value'
from /usr/lib/ruby/1.8/irb.rb:151:in `eval_input'
from /usr/lib/ruby/1.8/irb.rb:259:in `signal_status'
from /usr/lib/ruby/1.8/irb.rb:147:in `eval_input'
from /usr/lib/ruby/1.8/irb.rb:146:in `eval_input'
from /usr/lib/ruby/1.8/irb.rb:70:in `start'
from /usr/lib/ruby/1.8/irb.rb:69:in `catch'
from /usr/lib/ruby/1.8/irb.rb:69:in `start'
There is a field named 'group_id' instead of 'id' in the WHERE clause.
Can anybody please confirm this ?