I'm following a rails tutorial (Hartl) and it's been fine so far, but
something doesn't seem to be working right.
I have two basic models so far, "User" and "Micropost".
class User < ActiveRecord::Base
has_many :microposts
end
class Micropost < ActiveRecord::Base
belongs_to :user
end
If I do something like:
"first_user = User.first"
Then:
"first_user.microposts" - should return a hash of the first user's
microposts, but it just returns empty.
I'm sure there is data.
If I do "Micropost.first" it returns what I should see with
"first_user.microposts". If I do "Micropost.first.user_id" it does
return "1", so I know the association is there.
I did kill the rails server by pressing control+c, and then restarted
but that didn't make any difference.
Any ideas? I'm on Ubuntu 10.04/Ruby version 1.8.7/RubyGems 1.8.5/Rack
version 1.2/Rails version 3.0.9 if that helps.
I'm following a rails tutorial (Hartl) and it's been fine so far, but
something doesn't seem to be working right.
I have two basic models so far, "User" and "Micropost".
class User < ActiveRecord::Base
has_many :microposts
end
class Micropost < ActiveRecord::Base
belongs_to :user
end
If I do something like:
"first_user = User.first"
Then:
"first_user.microposts" - should return a hash of the first user's
microposts, but it just returns empty.
Interesting, but what I don't get, is "User.first" selects the first
user (regardless of their id). So "User.first.microposts" should give
me the first user's microposts I would think, no?
I'm wondering if as I was going through this tutorial, maybe I screwed
some things up?
I got confused since when I went to (localhost)/microposts, it showed me
the list of microposts with a "User" column with values of 1's and 2's
(I have two users), but in actuality their id's are 3 an 5 respectively,
so I'm not sure why there is a discrepancy.
Interesting, but what I don't get, is "User.first" selects the first
user (regardless of their id). So "User.first.microposts" should give
me the first user's microposts I would think, no?
If User.first.id is 3, then User.first.microposts will return the
microposts with user_id 3
It sounds like you used to have a User with id 1, which you then
deleted, leaving an orphaned micropost with no user behind.
I occasionally forget that I deleted some record and am puzzled why something isn't working. I am using MySQL and I find that it's helpful to have an easy way to look at the specifics of what's in the database so I keep SequelPro (<http://www.sequelpro.com/>\) running. Then I can see what the PK and FK values are at a glance ("yes, I did delete User with ID=1", for example). It also makes it easy to create test records quickly while I'm working out various algorithms.
Regardless of DB, remember you can handle situations like this using
e.g. :dependent => :destroy on an association, or even an after_destroy
callback (if you want to do something with the "orphaned" object").