Belongs_to with a custom class name not creating the correct foreign key in Rails 3

I am updating the application for 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 

View:

 <%- @products.each do |p| -%> <%= p.created_at %><br /> <%- end -%> 

I get this error in the Rails log:

 Mysql::Error: Unknown column 'products.user_id' in 'where clause': SELECT `products`.* FROM `products` WHERE (`products`.user_id = 1) 

It should see belongs_to :owner and look for a foreign key named owner_id . I even tried to explicitly set the foreign key, and this does not work. I also checked the beacon for a possible Rails 3 error, but no luck.

+6
ruby-on-rails activerecord belongs-to
source share
1 answer

You need to specify the foreign key in the has_many :products association, it does not automatically know that it displays belongs_to :owner .

This should work:

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

From rails docs:

: foreign_key

Specify the foreign key used for association. By default, this guesses that it is the name of the class in lowercase and the "_id" suffix. So, the Person class that makes the has_many association will use "person_id" as the default value: Foreign_key ..

+15
source share

All Articles