Should this even be a has_many :through association?
A Post belongs_to a User, and a User has_many Posts.
A Post also belongs_to a Topic, and a Topic has_many Posts.class User < ActiveRecord::Base
has_many :posts
end
class Topic < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :topic
end
Well, that's pretty simple and very easy to set up, but when I display a Topic, I not only want all of the Posts for that Topic, but also the user_name and the user_photo of the User that made that Post. However, those attributes are stored in the User model and not tied to the Topic. So how would I go about setting that up?
Maybe it can already be called since the Post model has two foreign keys, one for the User and one for the Topic?
Or, maybe this is some sort of "one-way" has_many through assiociation. Like the Post would be the join model, and a Topic would has_many :users, :through => :posts. But the reverse of this is not true. Like a User does NOT has_many :topics.
So would this even need to be has_many :though assoc开发者_开发知识库iation? I guess I'm just a little confused on what the controller would look like to call both the Post and the User of that Post for a give Topic.
Edit: Seriously, thank you to all that weighed in. I chose tal's answer because I used his code for my controller; however, I could have just as easily chosen either j.'s or tim's instead. Thank you both as well. This was so damn simple to implement. I think today might mark the beginning of my love affair with rails.
you can get the user_name
and user_photo
when displaying a topic and its posts...
something like:
@topic.posts.each do |post|
user_name = post.user.name
user_photo = post.user.photo
end
it's simple. sorry if i didn't understand your question very well.
Well, if what you want is display the user name of the author of a post, for example, you can do something like (not tested, but should work) :
@posts = topic.posts.all(:include => :user)
it should generate one request for all posts, and one for users, and the posts collection should have users.
in a view (haml here) :
- @posts.each do |post|
= post.user.name
= post.body
If I understand your question correctly, no, a has_many :through association is not required here.
If you wanted to display a list of all users that posted in a topic (skipping the post information), then it would be helpful.
You'll want to eager load the users from posts, though, to prevent n+1 queries.
精彩评论