belongs_to with a custom class_name not producing proper foreign key in Rails 3

Posted by Tony on Stack Overflow See other posts from Stack Overflow or by Tony
Published on 2010-06-15T14:01:33Z Indexed on 2010/06/15 14:32 UTC
Read the original article Hit count: 333

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.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord