Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 创建或更新与的关联有多个:通过_Ruby On Rails_Ruby_Associations_Has Many Through - Fatal编程技术网

Ruby on rails 创建或更新与的关联有多个:通过

Ruby on rails 创建或更新与的关联有多个:通过,ruby-on-rails,ruby,associations,has-many-through,Ruby On Rails,Ruby,Associations,Has Many Through,假设我有两个模型,导演和电影,还有第三个叫方向的模型。它们的定义如下: 电影: class Movie < ActiveRecord::Base has_many :directions has_many :directors, :through => :directions end class Director < ActiveRecord::Base has_many :directions has_many :movies, :through =>

假设我有两个模型,导演和电影,还有第三个叫方向的模型。它们的定义如下:

电影:

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
class电影:方向
结束
导演:

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
类控制器:方向
结束
说明:

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,或者在我创建或编辑电影时与先前存在的导演关联

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


接受的_嵌套的_属性_可以很好地工作,除非您在编辑我不想要的电影时可以实际编辑导演的姓名。我绝对不想更新/销毁实际的导演,只有关联。

您的电影实例有一个包含关系ID的director\u id数组。 因此,您可以轻松列出所有控制器,例如,哪些复选框,并要求用户检查关系

<% Director.all.each do |director| %>
  <%= check_box_tag 'movie[director_ids][]', director.id, @movie.directors.include?(director) %>
  <%= director.name # or whatever (title, etc) %>
<% end %>

<%= hidden_field_tag 'movie[director_ids][]', '' %>


(隐藏的_标记是当用户取消选中所有框时,因此导演ID将为空。)

谢谢,这让我有了一点收获。我最终会有相当多的导演(数百名),所以显示他们都不起作用,但我可以用一些AJAX搜索魔术来解决这个问题,这很好。我脑子里有一个特定的用例,我不知道如何实现。比如说,我和史蒂文·斯皮尔伯格一起导演了一部电影。然后我意识到他实际上并没有导演,但詹姆斯·卡梅隆导演了,我还没有詹姆斯·卡梅隆加入DB。使用您的解决方案,我可以取消选中史蒂文·斯皮尔伯格,但我如何将詹姆斯·卡梅隆加入并创建董事数据库记录和协会?谢谢