ruby-on-rails – belongs_to,自定义class_name在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的外键.我甚至尝试显式设置外键,但这不起作用.我还检查了灯塔的可能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..

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...