代码之家  ›  专栏  ›  技术社区  ›  Tony

属于具有自定义类名称的,在Rails 3中没有生成正确的外键

  •  6
  • Tony  · 技术社区  · 15 年前

    我正在将一个应用程序更新到Rails3,并且在创建自定义外键时遇到问题。我有这样的想法:

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

    Mysql::Error: Unknown column 'products.user_id' in 'where clause': SELECT     `products`.* FROM       `products` WHERE     (`products`.user_id = 1)
    

    它应该看到 belongs_to :owner 并查找一个名为 owner_id

    1 回复  |  直到 15 年前
        1
  •  14
  •   Community Mohan Dere    5 年前

    您需要在 has_many :products belongs_to :owner .

    这应该起作用:

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

    :外键

    指定外键 估计就是这个名字 用小写字母和“\u id”表示的类 后缀。所以一个人的职业 有许多协会会使用 “person\u id”作为默认值