A
A
Alexander Florinsky2014-12-23 00:56:51
Ruby on Rails
Alexander Florinsky, 2014-12-23 00:56:51

How to make a selection in ROR?

Hello.
I started studying rails and almost immediately ran into a banal problem.
The situation is this: there are buyers and each buyer has several orders.
The models look like this:

class User < ActiveRecord::Base
  has_many :order
end

class Order < ActiveRecord::Base
  belongs_to :user
end

There is a User#index controller that returns JSON with all users.
class UserController < ApplicationController
  def index
    @user = User.all
    render json: @user
  end
end

Is it possible, with one command, to make a selection from two tables: users and orders so that JSON would be formed that will contain all users and their orders? Or is it necessary to loop through the received users and make a request for each user?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Viktor Vsk, 2014-12-23
@flor_master

First, has_many :ordersafter all (in the plural)
In a simple way, you can do something like this:

class UsersController < ActionController::Base
   def index
     @users = Hash[User.all.map{ |u| [u.name, u.orders.to_a }].to_json
   end
end

But it would probably be right to look in the direction of rabl or builder, display @users = User.all, and then process orders in view.
Here is what jbuilder is: railscasts.com/episodes/320-jbuilder

B
Boris Penkovsky, 2014-12-24
@Able1991

@users.as_json :include => :orders

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question