简体   繁体   中英

populate object_id fields in rails query

I have two models. One named user, and one named orders. Users have an order_id field with the order's id. I have set up orders to belong to users and users to have many orders. Now I would like to have a view where I show some users, and each order for that user. Obviously it would be nice if I could just get one bit object that has the users and instead of the order_id , have the actual order. I know there are some languages where you can something like this:

found_user.populate(order_id)

Is there an option to do this in rails? I have seen the select function, but it doesn't seem to work, not with User.find() anyhow, which is what I am using.

Any ideas?

When you say order belongs to user , you should have user_id in orders table but not order_id in users table.

Now I would like to have a view where I show some users, and each order for that user.

And now in the view where you want to display the users and their orders, try the below code

<% @users.each do |user| %>
  <%= user.name %> #assuming you have name field in users table.
  <% user.orders.each do |order| %>
    <%= order.name %> #assuming you have name field in orders table.
  <% end %>
<% end %>

Where @users = User.all which is defined in the respected controller action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM