Get data from multiple models

Hi all,

I have a model Post and a model User. The post has a user_id foreign
key. What is the best way (railsway) to get all the posts from 1 user?
Like
user = User.find(id)
posts = user.Node.find()

This doesn’t work?

Thank,
Stijn

hi! try this

in model “Post” add the following line:
belongs_to :user, :class_name => ‘User’, :foreign_key => ‘user_id’

in model “User” add this
has_many :posts, :class_name => ‘Post’

then you can do
user = User.find(id)
posts = user.posts

Tarscher wrote:

Hi all,

I have a model Post and a model User. The post has a user_id foreign
key. What is the best way (railsway) to get all the posts from 1 user?
Like
user = User.find(id)
posts = user.Node.find()

user has_many :posts
post belongs_to :user

user = User.find(id)
posts = user.posts

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs