新手问题 请问有哪位能讲讲 inverse_of?

cqcn1991 · February 01, 2013 · Last by liuhui1226 replied at September 25, 2017 · 7353 hits

http://stackoverflow.com/questions/9296694/what-does-inverse-of-do-what-sql-does-it-generate 这里有讲到,但是依然不太清楚

看到 ruby-china 源码里面,很多源码里面貌似都有 可是 ruby on rails tutorial 里面完全没涉及到 如果按照 documentation 里面来说,

@post = Post.first
@tag = @post.tags.build :name => "ruby"
@tag.save

只有当用了:inverse_of 才能 save。可是完全无法理解啊!!!!这里的 taggable 到底是咋回事,太抽象了

class Taggable < ActiveRecord::Base
  belongs_to :post
  belongs_to :tag, :inverse_of => :taggings
end

主要是避免重复查询

class User
  has_one :profile
end

class Profile
  belongs_to :user
end

u = User.create
p = u.create_profile


u = User.last
p = u.profile
# 这里 p.user 其实就是 u,但是不用 inverse_of 的话,还是会去查询数据库,所以 object id 也不用,如果 u 更改了, p.user 需要 reload 才能看到修改
u.object_id # => 41737620
p.user.object_id # => 41695760

如果加了 inverse_of, p.user 就会直接引用 u

用了 inverse_of 之后 object_id 还是不一样啊 如何证明p.user 就会直接引用 u

class User < ActiveRecord::Base
  attr_accessible :login
  has_one :profile, :inverse_of => :user
end
class Profile < ActiveRecord::Base
  attr_accessible :name
  belongs_to :user
end

http://ruby-china.org/topics/8525 @doitian @iBachue 实际的例子,中间表的验证问题。

IChou in 关于 inverse_of 的困惑与探究 mention this topic. 17 Jun 11:52
Reply to qinfanpeng

给像我这样的新手提个醒吧,Rails4.1 之后就不用手动写 inverse_of 了,不过为了配合其他功能,比如 accepts_nested_attributes_for,还是手动加上保险一点。

如果你想学习学习,自己瞎搞搞,可以加上 inverse_of: false 试试,或者看看这篇文章https://ruby-china.org/topics/24998

You need to Sign in before reply, if you don't have an account, please Sign up first.