ITPUB??ì3
ITPUB论坛 » 动态语言 » has_many_through的一个问题

新一届的微软MVP评选已经开始,欢迎各位推荐!

标题: has_many_through的一个问题
离线 44sizi
中级会员



精华贴数 0
个人空间 0
技术积分 1146 (1562)
社区积分 0 (1032079)
注册日期 2006-7-15
论坛徽章:0
      
      

发表于 2006-8-7 13:16 
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]


只看该作者    顶部
离线 44sizi
中级会员



精华贴数 0
个人空间 0
技术积分 1146 (1562)
社区积分 0 (1032079)
注册日期 2006-7-15
论坛徽章:0
      
      

发表于 2006-8-7 13:17 
另外,

b2=Book.find(2)
b2.authors.create和b2.authors.build都包括失败。而b2.authorships.create也会包括一个错误。而b2.authorships.build则不会。

不知道这是为什么,请大侠帮忙解答一下.


只看该作者    顶部
离线 四紫
中级会员



精华贴数 0
个人空间 0
技术积分 1244 (1395)
社区积分 0 (1032065)
注册日期 2006-7-15
论坛徽章:0
      
      

发表于 2006-8-7 13:19 
since books and authors are many-to-many relationships, you should use has_many_belong_to_many relationships.
http://www.digitalmediaminute.co ... lationship-tutorial


只看该作者    顶部
离线 四紫
中级会员



精华贴数 0
个人空间 0
技术积分 1244 (1395)
社区积分 0 (1032065)
注册日期 2006-7-15
论坛徽章:0
      
      

发表于 2006-8-7 13:20 
findsun,第一个没有错误,@errors是空的
第二个问题,我一般都用b2.authors << an_author, authors.build是新建一个对象但不save, create和build一样但save. save完了自然有@errors,哪怕没错也包含一个,只是空而已。
habtm我不喜欢的地方是连接表的名字是约定的,而且不太直观。:through可以用更有描述性的表名, 另外以后要增加额外关联属性也方便很多。上次我看见一个巧妙的伪造别名方法使得构造自引用结构时也不需要用habtm了(http://blog.hasmanythrough.com/a ... rential-through)。

b2.authors << an_author判断很简单啊,成了就返回true,不成就false


只看该作者    顶部
 
    

相关内容


CopyRight 1999-2006 itpub.net All Right Reserved.
北京皓辰广域网络信息技术有限公司. 版权所有
E-mail:Webmaster@itpub.net
京ICP证:010037号 联系我们 法律顾问