has_many_through的一个问题
代码:
class Author < ActiveRecord::Base
has_many :authorships, :dependent=>true
has_many :books, :through => :authorships
end
class Book < ActiveRecord::Base
has_many :authorships, :dependent=>true
has_many :authors, :through => :authorships
end
class Authorship < ActiveRecord::Base
belongs_to :author
belongs_to :book
end
事先已经建好了数据库的表
代码:
Books:
id
name
Author:
id
name
Authorship:
id
book_id
author_id
然后使用下面的代码
代码:
a1 = Author.find(1)
b3 = Book.find(3)
a1b3 = b3.authorships.build()
a1b3.author = a1
a1b3.save()
虽然数据实际已经保存到数据库中了,但似乎有错误发生。
代码:
a2b3
=> #<Authorship:0xb7559b90 @author=#<Author:0xb754e4ac @attributes={"name"=>"author1", "id"=>"2"}>, @errors=#<ActiveRecord::Errors:0xb754ab68 @errors={}, @base=#<Authorship:0xb7559b90 ...>>, @attributes={"id"=>6, "author_id"=>2, "book_id"=>3}, @new_record=false>
各位大侠,不知道如何查看ActiveRecord::Errors呢?[/code]
|