小编Erl*_*son的帖子

创建或更新与has_many的关联:through

假设我有两个模型,Director和Movie,以及第三个名为Directions的连接模型.它们被定义为:

电影:

class Movie < ActiveRecord::Base
  has_many :directions
  has_many :directors, :through => :directions
end
Run Code Online (Sandbox Code Playgroud)

导向器:

class Director < ActiveRecord::Base
  has_many :directions
  has_many :movies, :through => :directions
end
Run Code Online (Sandbox Code Playgroud)

路线:

class Direction < ActiveRecord::Base
  belongs_to :movie
  belongs_to :director
end
Run Code Online (Sandbox Code Playgroud)

当我创建一部电影时,我希望能够使用提供的信息(名称和imdb_id)创建一个导演,或者根据imdb_id找到一个现有的导演,并将其与电影记录相关联.

从本质上讲,我不想删除或编辑导演.我只希望能够创建新的导演,如果他不存在基于他的imdb_id,或者在创建或编辑电影时与预先存在的导演关联.

我的问题是,如何在视图/控制器中链接所有这些?

accepts_nested_attributes_for工作正常,除非您在编辑我不想要的电影时可以实际编辑导演的名字.我完全没有兴趣更新/摧毁实际的董事,只有协会.

ruby ruby-on-rails associations has-many-through

5
推荐指数
1
解决办法
1117
查看次数