新手问题 rails 如何设置 Models 的关联字段?

topswim · December 06, 2012 · Last by uudui replied at December 06, 2012 · 3744 hits

我有两个 Models,如果用 has_many 关联起来两个 Models 是用 id 关联的!在删除一个 Model 条记录时,rails 默认会用 id 关联删除另一个 Model 的记录,现在我想自己设定这个关联字段可以吗?怎么设定?

设置:foreign_key => xxx

class Post < ActiveRecord::Base
  attr_accessible :content, :name, :title

  validates :name,  :presence => true
  validates :title, :presence => true,
                    :length => { :minimum => 5 }
  has_many :comments, :dependent => :destroy
end

:dependent => :destroy

#1 楼 @uudui 删除的时候只删除了主表,被关联的表没有删掉啊?

#2 楼 @woaigithub 不好意思你没有理解我的意思!?我的意思是重新设置 foreign_key,根据这个 foreign_key 删除其他表中的记录

举例子吧。 删除 post,然后删除 post 的 comment,因为 post 都不存在了,附属于 post 的 comment 没有意义。

难道你的需求是,删除 comment,然后删除 comment 对应的 post,这个好像有点不太好吧。

#7 楼 @woaigithub 删除 post,然后删除 post 的 comment,因为 post 都不存在了,附属于 post 的 comment 没有意义。

#8 楼 @woaigithub 没有意义所以干掉啊!

干掉就我这种做法。

:dependent => :destroy

#11 楼 @woaigithub 大哥,你这样是可以干掉,但是默认主键和外建都是 id !

posts 的主键是 id,comments 的外键是 post_id。


class Post

  has_one :author, :class_name => "User",  :foreign_key => "user_id"

end

#5 楼 @topswim 这个需要在关联的两个 model 中设置:foreign_key 如:

class Post < ActiveRecord::Base
  belongs_to :user, :foreign_key => :creator_id
end

class User < ActiveRecord::Base
  has_many :posts, :foreign_key => :creator_id, :dependent => :destroy
end
You need to Sign in before reply, if you don't have an account, please Sign up first.