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

1

5

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.

Finkle answered 15/6, 2010 at 14:1 Comment(0)
L
14

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..

Latvina answered 15/6, 2010 at 14:39 Comment(3)
this worked but i guess it's a bit strange that i didn't have to do it with my Rails 2 app. not sure it would be considered a bugFinkle
It should be the same in Rails 2. :)Latvina
I have two columns on my table that reference the User table. Do you know how I would set up the reference? I can't just say owner_id as suggested above because I need Owner and SubmittingUser. Thanks!Darla

© 2022 - 2024 — McMap. All rights reserved.