Skip to content

Instantly share code, notes, and snippets.

@armandofox
Created July 8, 2021 23:31
Show Gist options
  • Save armandofox/7e9140734d37ed46fd683e85519e9f65 to your computer and use it in GitHub Desktop.
Save armandofox/7e9140734d37ed46fd683e85519e9f65 to your computer and use it in GitHub Desktop.
association1.rb
# it would be nice if we could do this:
inception = Movie.where(:title => 'Inception')
alice,bob = Moviegoer.find(alice_id, bob_id)
# alice likes Inception, bob less so
alice_review = Review.new(:potatoes => 4)
bob_review = Review.new(:potatoes => 3)
# a movie has many reviews:
inception.reviews = [alice_review, bob_review]
# a moviegoer has many reviews:
alice.reviews << alice_review
bob.reviews << bob_review
# can we find out who wrote each review?
inception.reviews.map { |r| r.moviegoer.name } # => ['alice','bob']
@Douglas-Carneiro
Copy link

The second line returns an ActiveRecord Relation instead of a Movie instance, so the correct code would be:
inception = Movie.where(:title => 'Inception').first OR
inception = Movie.find_by(:title => 'Inception')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment