Join two models

Need some help with understanding the best way of doing the
following:

I have a user model and two models (link_post and text_post) i now
want to join the models together as post.
both link_post and text_post has a user_id column.

What a i want is to get
u = User.first
u.posts
to collect all link_post and text_post together.

Should this be done with a scope or with some model association ? I
don’t need a controller for posts just the self join.
But if i can get other scopes on “posts” it would be great… (like
published_on etc …)

On 16 December 2011 07:11, Niklas N. [email protected] wrote:

to collect all link_post and text_post together.

Should this be done with a scope or with some model association ? I
don’t need a controller for posts just the self join.
But if i can get other scopes on “posts” it would be great… (like
published_on etc …)

Have a look at the Rails Guide on ActiveRecord Associations. That
should get you started.

Colin

Thanks, got it sort of working. Would like to drop <
ActiveRecord::Base from Post (don’t want to create a table for Posts)
just the TextPost and LinkPost, will work on that tonight.
Thanks again.

/Niklas.

On 16 dic, 08:11, Niklas N. [email protected] wrote:

to collect all link_post and text_post together.

Should this be done with a scope or with some model association ? I
don’t need a controller for posts just the self join.
But if i can get other scopes on “posts” it would be great… (like
published_on etc …)

Looks like you could use inheritance here, with LinkPost and TextPost
inheriting from Post. Then user would ‘has_many :posts’ and that way
when you do:
u.posts
You would get both link_posts and text_posts

Also you’ll probably want to call the previous as:
User.includes(:posts).all

This way you ‘preload’ posts and save yourself from making an extra
sql request each time you hit a user in an iteration ( for more info.
google: n+1 query)