Ken
Ken

Reputation: 636

Need help understanding how ActiveRecord works

Take the following example of a basic forum.

class Forum < ActiveRecord::Base
  has_many :topics, :dependent => :destroy
end

class Topic < ActiveRecord::Base
  belongs_to :forum
  belongs_to :user
  has_many   :posts, :dependent => :destroy
end

class Post < ActiveRecord::Base
  belongs_to :topic
  belongs_to :user 
end

class User < ActiveRecord::Base
  has_many :posts
  has_many :topics
end

Now say I wanted to add the ability to fetch the "last post" information of each forum. My forum table has a column called "last_post_id" that holds the id of the last post made in said forum. If I understand how active record works, I would need to add a "has_one" relationship to my forum model and specify the primary key I want to use, like so:

class Forum < ActiveRecord::Base has_many :topics, :dependent => :destroy has_one :last_post, :class_name => 'Post', :primary_key => :last_post_id end

Then my query would look like this:

@forums = Forum.all(:include => [:last_post])

Is this right so far? But say I also wanted to fetch the user info who posted that last post. Well my post table has a "user_id" column that I could use. Do I need to create a "has_one" relationship like I did with the last_post? This doesn't seem to work:

class Forum < ActiveRecord::Base
  has_many :topics, :dependent => :destroy
  has_one :last_post  , :class_name => 'Post', :primary_key => :last_post_id 
  has_one :last_poster, :class_name => 'User', :primary_key => :last_post_user_id
end

How can I use the value of the last_post.user_id to fetch the user info from the user table. The raw query would look something like this:

SELECT forums.*, 
       last_post.id              as last_post_id,
       last_post.user_id         as last_post_user_id,
       last_post_user.username   as last_post_username,
  FROM forums as forums
 INNER JOIN posts  as last_post      ON last_post.id       = forums.last_post_id
 INNER JOIN users  as last_post_user ON last_post.user_id  = last_post_user.id

Notice that I grab the user info using the last_post.user_id. How do you do that using rails? The goal is to have the following variables available for rendering the last post info in the views.

forum.last_post.date       # the last post object
forum.last_poster.username # the user object who created the last post 

Am I understanding how this works correctly, what am I doing wrong?

Upvotes: 0

Views: 679

Answers (1)

Webjedi
Webjedi

Reputation: 4737

I would say that the last_poster on the forum model seems necessary. Since there's only one I might just let that get loaded lazily when I called that info in the view.

So when you are working in your view just do forum.last_post.user.username

Upvotes: 2

Related Questions