belongs_to with a custom class_name not producing proper foreign key in Rails 3
- by Tony
I am updating an application to Rails 3 and I am having trouble creating a custom foreign key. I have something like this:
class Product < ActiveRecord::Base
belongs_to :owner, :class_name => 'User'
...
end
class User < ActiveRecord::Base
has_many :products
...
end
class ProductsController < ApplicationController
before_filter :authenticate_user!
def index
@products = current_user.products
end
end
The view:
<%- @products.each do |p| -%>
<%= p.created_at %><br />
<%- end -%>
I get this error in my Rails log:
Mysql::Error: Unknown column 'products.user_id' in 'where clause': SELECT `products`.* FROM `products` WHERE (`products`.user_id = 1)
It should see the belongs_to :owner and look for a foreign key called owner_id. I even tried explicitly setting the foreign key and that does not work. I also checked lighthouse for a possible Rails 3 bug but no luck.