Обратите внимание, что следующее для Rails v2
script/generate model Movie id:primary_key name:string
script/generate model Actor id:primary_key movie_id:integer celeb_id:integer cast_name:string cast_type:string
script/generate model Celeb id:primary_key name:string
model/movie.rb
class Movie < ActiveRecord::Base
has_many :actors
has_many :celebs, :through => :actors
end
model/celeb.rb
class Celeb < ActiveRecord::Base
has_many :actors
has_many :movies, :through => :actors
end
model/actor.rb
class Actor < ActiveRecord::Base
belongs_to :movie
belongs_to :celeb
end
Проверка связей с консолью ruby rails в папке приложения
>script/console
>m = Movie.new
>m.name = "Do Androids Dream Of Electric Sheep"
>m.methods.sort #this will list the available methods
#Look for the methods 'actors' and 'celebs' - these
#are the accessor methods built from the provided models
>m.actors #lists the actors - this will be empty atm
>c = Celeb.new
>c.name = "Harrison Ford"
>m.celebs.push(c) #push Harrison Ford into the celebs for Blade Runner
>m.actors #Will be empty atm because the movie hasnt been saved yet
>m.save #should now save the Movie, Actor and Celeb rows to relevant tables
>m.actors #Will now contain the association for
#Movie(id : 1, name : "Do Androids..") - Actor(id : 1, movie_id : 1, celeb_id : 1) -
#Celeb(id : 1, name : "Harrision Ford")
>m = Movie.new #make a new movie
>m.name = "Star Wars"
>m.celebs.push(c) #associated the existing celeb with it
>m.save
>movies = Movie.all #should have the two movies saved now
>actors = Actor.all #should have 2 associations
>this_actor = Actor.first
>this_actor.cast_type = "ACTOR"
>this_actor.save
Тогда, возможно, вам захочется посмотреть на Ryan Bates 'Railcasts http://railscasts.com # 47 (два "многие ко многим") и # 73, # 74, # 75 (сложные формы, части 1-3). ,
На веб-странице имеется обновленная версия кода формы «многие ко многим» для # 75.