带有自定义class_name的belongs_to在Rails 3中不生成正确的外键

发布于 2024-09-06 02:09:41 字数 858 浏览 5 评论 0原文

我正在将应用程序更新到 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 的外键。我什至尝试显式设置外键,但这不起作用。我还检查了 lighthouse 是否存在可能的 Rails 3 bug,但没有成功。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半枫 2024-09-13 02:09:41

您需要在 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”为默认值
:外键..

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文