我正在将应用程序更新到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文档:

关于ruby-on-rails - 带有自定义class_name的Emirates_to不会在Rails 3中产生正确的外键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3045863/

10-13 04:15