Roh*_*hit 9 ruby ruby-on-rails associations has-many-through belongs-to
I have three models, each having the following associations:
class Model1 < ActiveRecord::Base
has_many :model2s
has_many :model3s
end
class Model2 < ActiveRecord::Base
belongs_to :model1
has_many :model3s, :through => :model1 # will this work? is there any way around this?
end
class Model3 < ActiveRecord::Base
belongs_to :model1
has_many :model2s, :through => :model1 # will this work? is there any way around this?
end
Run Code Online (Sandbox Code Playgroud)
As you can see in the commented text, I have mentioned what I need.
您只需创建访问它的方法
class Model2 < ActiveRecord::Base
belongs_to :model1
def model3s
model1.model3s
end
end
Run Code Online (Sandbox Code Playgroud)
或者,您可以将model3s方法委托给model1
class Model2 < ActiveRecord::Base
belongs_to :model1
delegate :model3s, :to => :model1
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5844 次 |
| 最近记录: |