Rails 想得到一个模型下我写过哪些 “has_many”,这个有办法吗?

hexawing · 2013年06月14日 · 最后由 heliang7 回复于 2013年06月14日 · 2613 次阅读

如题。 更进一步,能知道每个 has_many 下我对应了哪个表吗?

has_many :jobs, :foreign_key => 'user_id', :class_name => "Task"

比如上面这个模型,能得到这个Task吗?

呃,刚问完就自己找到了……

http://stackoverflow.com/questions/8371574/is-there-a-way-to-list-all-belongs-to-associations

class Thing < ActiveRecord::Base
  belongs_to :foo
  belongs_to :bar
end

# this would return a hash of all `belongs_to` reflections, in this case:
# { :foo => (the Foo Reflection), :bar => (the Bar Reflection) }
reflections = Thing.reflections.select do |association_name, reflection| 
  reflection.macro == :belongs_to
end

不删可以吗,权当备忘了……

看看 Model.reflections 里面有些什么,也许有你想要的。

#2 楼 @yanhao 谢谢,我已经找到了,嘿嘿

学习了。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号