Humberto Tellechea Humberto Tellechea - 18 days ago 5
React JSX Question

Is there a way to store an array of Objects and the associated instance of another table in a single variable?

I have two associated tables: Users and Posts.

Post
belongs_to
User
, so there is a foreign key
user_id
linking it to the Users table.
Is there a way in which I can store an array of Post objects and its associated User object in a single variable?

@posts = Post.all


will return an array of all existing Posts, and

@user = Post.find(1).user


will return the first Post's corresponding User. Is there a way to combine these two queries in one?

If you are wondering why do I need this, I am working with ReactJS and I want to pass this variable as props so I can access the
User
attributes of a
Post
in my component.
Hope you guys can help!

Answer

Not entirely sure what you are after but if it's just the user associated with the first post then simply do:

@user = Post.first.user

If you want to iterate through each post to find the user then something like:

Posts.all.each do |post|
  @users << post.user      
end

If you want to just find the first post associated with each user, then ensure you have the relationship mapped correctly and iterate through each user instead:

class User < ActiveRecord::Base
  has_many :posts
end

User.all.each do |user|
  @posts << user.posts.first
end
Comments