Setting a :has_many :through association on a belongs_to association Ruby on Rails

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.

shi*_*ara 9

您只需创建访问它的方法

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)

  • 作为更新,自Rails 4.2起,您现在可以通过`belongs_to`关系执行`has_many`和`has_one` (5认同)