5

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.

1 Answers1

3

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...

<% 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][]', '' %>

(the hidden_tag is when the user uncheck all the boxes, so that director_ids will be empty.)

Nicolas Blanco
  • 11,164
  • 7
  • 38
  • 49
  • Thanks, that gets me partway there. I will eventually have quite a few directors (in the hundreds) so displaying them all will not work but I can fix that with some AJAX search magic which is fine. I have one specific use case in mind which I'm not sure how to implement. Let's say I create a movie with Steven Spielberg as a director. Then I realize he didn't actually direct it but James Cameron did and I don't have James Cameron in the DB yet. With your solution I could uncheck Steven Spielberg but how would I add James Cameron in and create the Director DB record and association? Thanks! – Erlingur Þorsteinsson Jan 31 '11 at 00:59