Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Note the following is for Rails v2 </p> <pre><code> 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 &lt; ActiveRecord::Base has_many :actors has_many :celebs, :through =&gt; :actors end model/celeb.rb class Celeb &lt; ActiveRecord::Base has_many :actors has_many :movies, :through =&gt; :actors end model/actor.rb class Actor &lt; ActiveRecord::Base belongs_to :movie belongs_to :celeb end </code></pre> <p>Test the associations with the ruby rails console in the application folder</p> <pre><code>&gt;script/console &gt;m = Movie.new &gt;m.name = "Do Androids Dream Of Electric Sheep" &gt;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 &gt;m.actors #lists the actors - this will be empty atm &gt;c = Celeb.new &gt;c.name = "Harrison Ford" &gt;m.celebs.push(c) #push Harrison Ford into the celebs for Blade Runner &gt;m.actors #Will be empty atm because the movie hasnt been saved yet &gt;m.save #should now save the Movie, Actor and Celeb rows to relevant tables &gt;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") &gt;m = Movie.new #make a new movie &gt;m.name = "Star Wars" &gt;m.celebs.push(c) #associated the existing celeb with it &gt;m.save &gt;movies = Movie.all #should have the two movies saved now &gt;actors = Actor.all #should have 2 associations &gt;this_actor = Actor.first &gt;this_actor.cast_type = "ACTOR" &gt;this_actor.save </code></pre> <p>Then you'll probably want to check out Ryan Bates' Railcasts <a href="http://railscasts.com" rel="nofollow">http://railscasts.com</a> #47 (Two Many-to-Many), and #73, #74, #75 (Complex forms parts 1-3). </p> <p>There's an updated version of the many-to-many form code on the webpage for #75.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload