创建或更新与 has_many 的关联:through
假设我有两个模型:Director 和 Movie,第三个连接模型称为 Directions。它们的定义如下:
电影:
class Movie < ActiveRecord::Base
has_many :directions
has_many :directors, :through => :directions
end
导演:
class Director < ActiveRecord::Base
has_many :directions
has_many :movies, :through => :directions
end
方向:
class Direction < ActiveRecord::Base
belongs_to :movie
belongs_to :director
end
当我创建一部电影时,我希望能够创建一个具有提供的信息(姓名和 imdb_id)或根据 imdb_id 查找现有导演并将其与电影记录关联。
本质上,我永远不想删除或编辑导演。我只希望能够在根据 imdb_id 不存在新导演的情况下创建新导演,或者在创建或编辑电影时与预先存在的导演关联。
我的问题是,如何在视图/控制器中将所有这些链接起来?
accepts_nested_attributes_for 工作正常除非当你编辑我不想要的电影时你实际上可以编辑导演的名字。我绝对没有兴趣更新/销毁实际的董事,只有协会。
Say I have two models, Director and Movie, and a third join model called Directions. They are defined as such:
Movie:
class Movie < ActiveRecord::Base
has_many :directions
has_many :directors, :through => :directions
end
Director:
class Director < ActiveRecord::Base
has_many :directions
has_many :movies, :through => :directions
end
Directions:
class Direction < ActiveRecord::Base
belongs_to :movie
belongs_to :director
end
When I create a movie I want to be able to either create a director with the supplied information (name and imdb_id) or find an existing director based on the imdb_id and associate it with the Movie record.
Essentially, I don't want to delete or edit a director, ever. I only want to be able to create a new director if he doesn't exist based on his imdb_id, or associate with a pre-existing director when I am creating or editing a movie.
My question is, how do I link all this up in the view/controller?
accepts_nested_attributes_for works fine except you can actually edit the director's name when you're editing a movie which I don't want. I have absolutely no interest in updating/destroying the actual directors, only the associations.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的电影实例有一个director_ids 数组,其中包含关系的id。
因此,您可以轻松列出所有导演,例如哪些复选框,并要求用户检查关系...
(hidden_tag 是当用户取消选中所有框时,这样director_ids 将为空。)
Your movie instance has a director_ids array which contains the ids of the relations.
So you can easily list all the directors for example which checkboxes and ask the user to check the relations...
(the hidden_tag is when the user uncheck all the boxes, so that director_ids will be empty.)