带有自定义class_name的belongs_to在Rails 3中不生成正确的外键
我正在将应用程序更新到 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在
has_many :products
关联上指定外键,它不会自动知道它镜像belongs_to :owner
。这应该有效:
来自 Rails 文档:
You need to specify the foreign key on the
has_many :products
association, it does not automagically know that it mirrors thebelongs_to :owner
.This should work:
From the rails docs: