L
L
legolas44442015-08-11 13:57:32
Ruby on Rails
legolas4444, 2015-08-11 13:57:32

How to return data from different entities in one request?

Hello! I want to build an application, for example, twitter. It should work like this:
1. The base template is loaded.
2. We send an Ajax request (for example, to get /user/{username})
3. We get a json response with all tweets, tags, information about the user, etc. 4. And on the front end, this whole thing will be sorted out by
AngularJs
volume: how to give away all the data so gracefully at once? I am new to rails. In php I did something like this:

//Метод Контроллера для роута get /user/{current_user}
public function($current_user) {
  $tags = new Tags();
  $user = new User();
  $profile = [
      "tags" => $tags->get_tag($current_user)
      "profile_info" => $user->get_info($current_user) 
      ....
  ] 
  return json_encode($profile)
}

Can this be done more elegantly in rails, or is the principle the same? If not difficult, then with code examples. Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg, 2015-08-11
@legolas4444

If I understand correctly, then:
User model:
has_many :tags
Tag model:
belongs_to :user

@user = User.find(params[:user_id])
render json: {
  tags: @user.tags,
  profile_info: @user
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question