at.*_*at. 3 activerecord ruby-on-rails belongs-to ruby-on-rails-3 ruby-on-rails-3.2
有没有一种方法through可以在belongs_to关系中使用该选项?选项中没有提及关于Emirates_to的Rails文档through,为什么不呢?我想做以下事情:
class Lesson < ActiveRecord::Base
attr_accessible :name, :lesson_group_id
belongs_to :lesson_group
belongs_to :level, through: :lesson_group
end
class LessonGroup < ActiveRecord::Base
attr_accessible :name, :level_id
belongs_to :level
has_many :lessons
end
class Level < ActiveRecord::Base
attr_accessible :number
has_many :lesson_groups
end
Run Code Online (Sandbox Code Playgroud)
然后我可以做类似的事情Lesson.first.level。使用最新的稳定Rails(截至目前为3.2.9)。
在您给的链接中:
指定与另一个类的一对一关联。仅当此类包含外键时,才应使用此方法。
我认为您应该使用has_one :level, through: :lesson_group,例如:
class Lesson < ActiveRecord::Base
attr_accessible :name, :lesson_group_id
belongs_to :lesson_group
has_one :level, through: :lesson_group
end
class LessonGroup < ActiveRecord::Base
attr_accessible :name, :level_id
belongs_to :level
has_many :lessons
end
class Level < ActiveRecord::Base
attr_accessible :number
has_many :lesson_groups
end
Run Code Online (Sandbox Code Playgroud)
有关以下选项的文档的一部分has_one:
:通过
指定用于执行查询的联接模型。:class_name,:primary_key和:foreign_key的选项将被忽略,因为关联使用源反射。您只能在联接模型上通过has_one或belongs_to关联使用:through查询。
他们在这里谈论了这一点: Rails has_one:through association