2010-04-21 67 views
19

我不知道什么地方出了问题,但我无法得到belongs_to:class_name选项。有人可以启发我吗?非常感谢!belongs_to与:class_name选项失败

这是从我的代码片段。

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 的Rails 2.3.5

回答

6

应该

belongs_to :user, :foreign_key => 'author_id' 

如果你的外键是作者ID。由于您实际上拥有用户类,因此您的图书必须属于:用户。

52
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_iduser_id。然后您可以删除:foreign_key选项。

+6

我在乎具有良好的外键。我不会应用关于重命名该列的建议,因为当列名称正确时,它更清楚发生了什么。 – 2010-04-21 19:33:28

+1

无论哪种方式工作。无论对你和你的团队有意义,都是正确的做法。 :) – 2010-04-21 19:53:24

+2

并认为class_name:'用户'将是足够的 – Donato 2015-03-30 21:25:57

0

我做了这种方式:

迁移 -

class AddAuthorToPosts < ActiveRecord::Migration 
    def change 
    add_reference :posts, :author, index: true 
    add_foreign_key :posts, :users, column: :author_id 
    end 
end 

类岗位

belongs_to :author, class_name: "User"