有一种情况,是这样的c属于b,b属于a,但是我们有时候想建立c属于a的关系,也就是c.a替代原来的c.b.a,那么可以使用through和has_one的结合使用来实现这个.
例如
1)
class A
has_one :b
end
class B
belongs_to :a
has_one :c
end
class C
belongs_to :b
has_one :a, :through => b
end
注意: belongs_to 不能和through一起使用,至于原因,我看了rails官方解释,但是看不懂.
2)
还有一些其他的解决方式,例如delegate也可以解决这个问题
class A
has_one :b
end
class B
belongs_to :a
has_one :c
end
class C
belongs_to :b
delegate :a, :to => :b, :allow_nil => true
end
例如
1)
class A
has_one :b
end
class B
belongs_to :a
has_one :c
end
class C
belongs_to :b
has_one :a, :through => b
end
注意: belongs_to 不能和through一起使用,至于原因,我看了rails官方解释,但是看不懂.
2)
还有一些其他的解决方式,例如delegate也可以解决这个问题
class A
has_one :b
end
class B
belongs_to :a
has_one :c
end
class C
belongs_to :b
delegate :a, :to => :b, :allow_nil => true
end