Humberto Tellechea Humberto Tellechea - 1 year ago 51
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.

, so there is a foreign key
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
attributes of a
in my component.
Hope you guys can help!

Answer Source

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      

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

User.all.each do |user|
  @posts << user.posts.first
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download