This is probably a dumb question, but I can't seem to find a good answer. I want to know the best way to refer back to the model that an object belongs to.
For example:
class User < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :users
end
So, to get the user's posts, I can use user.posts, but to get the post's user, I cannot do the reverse: post.user
If I add a "user" method to the Post model, it works, but it doesn't seem to be the best way.
class Post < ActiveRecord::Base
belongs_to :users
def user
User.find(self.user_id)
end
end
If you look at this blog post http://www.fortytwo.gr/blog/18/9-Essential-Rails-Tips as an example, you can see that the author uses post.user.username, which doesn't work out of the box as well as :include => [:user], which also doesn't work, even with the "user" method in the Post model.
I know this is rudimentary, so thanks for your patience. I just want to know the best way to accomplish this relation.
My main goal is to write "finds" using nested includes, which refer back to the user like so:
post = Post.find(:all, :include => [:user])
When I try this, I get "ActiveRecord::ConfigurationError: Association named 'user' was not found; perhaps you misspelled it?"
Thanks a lot.