views:

137

answers:

1

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.

+4  A: 

I'm a bit new to Rails, but this should work automatically...

Ah - you've named the parent class in Post as belongs_to :users; but because it only belongs to a single user, Rails is expecting belongs_to :user (or, of course, belongs_to :users, :class_name => "User").

That is:

class Post < ActiveRecord::Base
  belongs_to :user
end

should do the job.

Chris
Thanks. This is officially the dumbest question I've ever asked. Can't believe I didn't see that. I wonder why it even works if you make it plural...
Shagymoe