belongs_to的有:将class_name选项失败 [英] belongs_to with :class_name option fails
本文介绍了belongs_to的有:将class_name选项失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道哪里出了问题,但我不能让belongs_to的的工作:将class_name选项。可能有人开导我。非常感谢!
下面是我的code剪断。
类CreateUsers< ActiveRecord的::迁移
高清self.up
CREATE_TABLE:用户做| T |
t.text:名称
结束
结束
高清self.down
drop_table:用户
结束
结束
################################################## ###
类CreateBooks< ActiveRecord的::迁移
高清self.up
CREATE_TABLE:书做| T |
t.text:标题
t.integer:AUTHOR_ID,:空=>假
结束
结束
高清self.down
drop_table:书籍
结束
结束
################################################## ###
类用户的LT;的ActiveRecord :: Base的
的has_many:书籍
结束
################################################## ###
类Book<的ActiveRecord :: Base的
belongs_to的:作者:=将class_name> 用户,:验证=>真正
结束
################################################## ###
类BooksController中<的ApplicationController
DEF创建
用户= User.new({:名称=>吴宇森'})
user.save
@failed_book = Book.new({:标题=>失败!,:作者=> @user})
@ failed_book.save#失踪AUTHOR_ID
@success_book = Book.new({:标题=>'好天',:AUTHOR_ID => @ user.id})
@ success_book.save#没有错误!
结束
结束
环境:
1.9.1-P387 Rails的2.3.5
解决方案
类用户的LT;的ActiveRecord :: Base的
的has_many:书:foreign_key => AUTHOR_ID
结束
类Book<的ActiveRecord :: Base的
belongs_to的:作者:=将class_name> 用户,:foreign_key => AUTHOR_ID',:验证=>真正
结束
做的最好的事情是改变你的迁移和修改 AUTHOR_ID
到 USER_ID
。然后你就可以删除:foreign_key
选项
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!
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
解决方案
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_id
to user_id
. Then you can remove the :foreign_key
option.
这篇关于belongs_to的有:将class_name选项失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文