Ruby-on-rails 带有 :class_name 选项的belongs_to 失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2684843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
belongs_to with :class_name option fails
提问by crackpot
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_name 选项让belongs_to 工作。有人可以启发我。非常感谢!
Here is a snip from my code.
这是我的代码片段。
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
environment:
环境:
ruby 1.9.1-p387 Rails 2.3.5
红宝石 1.9.1-p387 导轨 2.3.5
回答by Tony Fontenot
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
The best thing to do is to change your migration and change author_idto user_id. Then you can remove the :foreign_keyoption.
最好的办法是更改您的迁移并更改author_id为user_id. 然后您可以删除该:foreign_key选项。
回答by Evgeny Shadchnev
It should be
它应该是
belongs_to :user, :foreign_key => 'author_id'
if your foreign key is author id. Since you actually have User class, your Book must belong_to :user.
如果您的外键是作者 ID。由于您实际上有 User 类,因此您的 Book 必须属于 :user。
回答by Lijun Guo
migration
移民
t.belongs_to :author, foreign_key: { to_table: :users }
working on rails 5
在轨道上工作 5
回答by rld
I do in this way:
我这样做:
Migration -
移民 -
class AddAuthorToPosts < ActiveRecord::Migration
def change
add_reference :posts, :author, index: true
add_foreign_key :posts, :users, column: :author_id
end
end
class Post
班级帖子
belongs_to :author, class_name: "User"

