【问题标题】:belongs_to with a custom class_name not producing proper foreign key in Rails 3具有自定义 class_name 的 belongs_to 在 Rails 3 中没有产生正确的外键
【发布时间】:2010-06-15 14:01:33
【问题描述】:

我正在将应用程序更新到 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 错误,但没有运气。

【问题讨论】:

    标签: ruby-on-rails activerecord belongs-to


    【解决方案1】:

    您需要在has_many :products 关联上指定外键,它不会自动知道它反映了belongs_to :owner

    这应该可行:

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

    来自 rails 文档:

    :foreign_key

    指定外键 用于协会。默认情况下 这被猜测是这个的名字 小写的类和“_id” 后缀。所以一个 Person 类 has_many 关联将使用 “person_id”作为默认值 :foreign_key..

    【讨论】:

    • 这行得通,但我想我不必用我的 Rails 2 应用程序来做这件事有点奇怪。不确定它是否会被视为错误
    • 在 Rails 2 中应该是一样的。:)
    • 我的表中有两列引用了 User 表。你知道我将如何设置参考吗?我不能只说上面建议的 owner_id,因为我需要 Owner 和 SubmittingUser。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-05-28
    • 2011-09-11
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    相关资源
    最近更新 更多