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

Tony picture Tony · Jun 15, 2010 · Viewed 8.1k times · Source

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.

Answer

elektronaut picture elektronaut · Jun 15, 2010

You need to specify the foreign key on the has_many :products association, it does not automagically know that it mirrors the belongs_to :owner.

This should work:

class User < ActiveRecord::Base
  has_many :products, :foreign_key => 'owner_id'
...
end

From the rails docs:

:foreign_key

Specify the foreign key used for the association. By default this is guessed to be the name of this class in lower-case and "_id" suffixed. So a Person class that makes a has_many association will use "person_id" as the default :foreign_key..