ruby-on-rails – belongs_to,自定义class_name在Rails 3中不生成正确的外键

前端之家收集整理的这篇文章主要介绍了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..

猜你在找的Ruby相关文章