带有 :class_name 选项的belongs_to 失败 [英] belongs_to with :class_name option fails

查看:22
本文介绍了带有 :class_name 选项的belongs_to 失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道出了什么问题,但我无法使用 :class_name 选项让belongs_to 工作.有人可以启发我.非常感谢!

I have no idea what went wrong but I can't get belongs_to work with :class_name option. Could somebody enlighten me. Thanks a lot!

这是我的代码片段.

class CreateUsers < ActiveRecord::Migration
    def self.up
        create_table :users do |t|
            t.text :name
        end
    end

    def self.down
        drop_table :users
    end
end

#####################################################

class CreateBooks < ActiveRecord::Migration
    def self.up
        create_table :books do |t|
            t.text :title
            t.integer :author_id, :null => false
        end
    end

    def self.down
        drop_table :books
    end
end

#####################################################

class User < ActiveRecord::Base
    has_many: books
end

#####################################################

class Book < ActiveRecord::Base
    belongs_to :author, :class_name => 'User', :validate => true
end

#####################################################

class BooksController < ApplicationController
    def create
        user = User.new({:name => 'John Woo'})
        user.save
        @failed_book = Book.new({:title => 'Failed!', :author => @user})
        @failed_book.save # missing author_id
        @success_book = Book.new({:title => 'Nice day', :author_id => @user.id})
        @success_book.save # no error!
    end
end

环境:

红宝石 1.9.1-p387导轨 2.3.5

ruby 1.9.1-p387 Rails 2.3.5

推荐答案

class User < ActiveRecord::Base
  has_many :books, :foreign_key => 'author_id'
end

class Book < ActiveRecord::Base
  belongs_to :author, :class_name => 'User', :foreign_key => 'author_id', :validate => true
end

最好的办法是更改您的迁移并将 author_id 更改为 user_id.然后您可以删除 :foreign_key 选项.

The best thing to do is to change your migration and change author_id to user_id. Then you can remove the :foreign_key option.

这篇关于带有 :class_name 选项的belongs_to 失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆