Note that there are some explanatory texts on larger screens.

plurals
  1. PObelongs_to / has_many not behaving as expected in Rails console
    text
    copied!<p>models:</p> <pre><code>class Person &lt; ActiveRecord::Base attr_accessible :email, :first, :last, :uuid, :books has_many :books end class Book &lt; ActiveRecord::Base belongs_to :person attr_accessor :blurb, :published, :title, :person attr_accessible :person end </code></pre> <p>I created a <code>Person</code> using the <strong>Rails 3.2.8 console</strong> like this:</p> <pre><code>person = Person.create!( {:first =&gt; "John", :last =&gt; "Doe"} ) </code></pre> <p>and then created a <code>Book</code></p> <pre><code>book = Book.create!( {:title =&gt; "Ruby for Dummies"} ) </code></pre> <p>I then try to associate them like this:</p> <pre><code>person.books &lt;&lt; book </code></pre> <p>When I query the person for books, I get an array with the book I created, but when I query the book for the person it belongs to, I get nil. I expected to get the person, given that all information was persisted (I see the SQL commands and I checked the database and the data is correct, i.e. the row in the book table points back to the person id it should.)</p> <p>What am I missing?</p> <p>thanks</p> <p>Edit- Schema:</p> <pre><code>CREATE TABLE `persons` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `first` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci', `last` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci', `uuid` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci', `email` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci', `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL, PRIMARY KEY (`id`) ) COLLATE='utf8_unicode_ci' ENGINE=InnoDB AUTO_INCREMENT=2; CREATE TABLE `books` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `title` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci', `blurb` TEXT NULL COLLATE 'utf8_unicode_ci', `published` TINYINT(1) NULL DEFAULT NULL, `person_id` INT(11) NULL DEFAULT NULL, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL, PRIMARY KEY (`id`) ) COLLATE='utf8_unicode_ci' ENGINE=InnoDB AUTO_INCREMENT=3; </code></pre>
 

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