我正在更新Rails 3的应用程序,我在创建自定义外键时遇到问题.我有这样的事情:
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
风景:
<%- @products.each do |p| -%> <%= p.created_at %><br /> <%- end -%>
我在Rails日志中收到此错误:
MysqL::Error: Unknown column 'products.user_id' in 'where clause': SELECT `products`.* FROM `products` WHERE (`products`.user_id = 1)
它应该看到belongs_to:owner并查找名为owner_id的外键.我甚至尝试显式设置外键,但这不起作用.我还检查了灯塔的可能Rails 3错误,但没有运气.
解决方法
您需要在has_many:products关联上指定外键,它不会自动知道它镜像belongs_to:owner.
这应该工作:
class User < ActiveRecord::Base has_many :products,:foreign_key => 'owner_id' ... end
来自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..