has_many:通过,3方式加入

时间:2013-03-08 04:14:23

标签: ruby-on-rails ruby-on-rails-3.1 has-many-through

我有一个有很多CostumedActors的Play。 CostumedActor是Actors和Costumes的连接,它们具有多对多的关系。

这似乎是一种非常常见的模式,但我不清楚在rails中执行此操作的最佳方式。

我目前将其设置为3向连接关联,如下所示:

class Play < ActiveRecord::Base
  has_many :costumed_actors
  has_many :actors, :through => costumed_actors
  has_many :costumes,:through => costumed_actors
end

class CostumedActor < ActiveRecord::Base
  belongs_to :play
  belongs_to :costume
  belongs_to :actor
end

class Costume < ActiveRecord::Base
  has_many :actors, :through => costumed_actors
  has_many :plays, :through => costumed_actors
end

class Actor < ActiveRecord::Base
  has_many :costumes, :through => costumed_actors
  has_many :plays, :through => costumed_actors
end

Rails没有完美地处理这个问题。如果我想在剧中看到演员或服装,没问题:

play.costumes
play.actors  

但是,如果我想看一个演员穿的服装,我不能做

play.actors.costumes

在这种情况下,.costumes为我提供了所有演员穿的所有服装,不仅仅是当前的演出。

我必须做类似的事情:

play.costumed_actors.where(:actor => @actor).map {|x| x.costumes}

或更干净,通过向has_many:通过关联

添加辅助方法
class Play
  has_many :costumes, :through => costumed_actors do
    def for_actor(actor)
      where("costumed_actors.actor_id = ?", actor) if !actor.nil?
    end
  end
end

play.costumes.for_actor(@actor)

此外,添加关联无法正常工作。我希望能够做一些像

这样的事情
Play.actors << actor.with_costume(costume)

但我看不出如何分阶段关联辅助方法,或者即使这种方法是可行的。

这是表示此方案的最佳方式吗?如果是,这是读取/写入关联记录的最佳方式吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

class Play
  has_many :actors_costumes, :through => :actors, :source => :costumes
end

你可以按照以下方式获得演员服装:

play.actors_costumes