加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – belongs_to,自定义class_name在Rails 3中不生

发布时间:2020-12-16 21:30:06 所属栏目:百科 来源:网络整理
导读:我正在更新Rails 3的应用程序,我在创建自定义外键时遇到问题.我有这样的事情: class Product ActiveRecord::Base belongs_to :owner,:class_name = 'User'...endclass User ActiveRecord::Base has_many :products...endclass ProductsController Applicati
我正在更新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..

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读