简体   繁体   中英

Creating or updating association with has_many :through

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM