在Rails 5中的一个方法中显示两个表数据

时间:2017-01-05 08:55:58

标签: ruby-on-rails ruby ruby-on-rails-5

我已使用以下代码填充User.all查询以获取所有用户信息。

def index
  @users = User.all
  if @users.exists?
    render json: @users
  else
    render json: { 'status' => 'S1000', 'description' => 'No users are registered' }
  end
end

它会重新包含所有用户详细信息,如下面的

[
  {
    "id": 13,
    "first_name": "Gunapala",
    "last_name": "Ratmalana",
    "email": "guna@gmai.com",
    "contact_number": "97866565",
    "user_name": "gunapala",
    "password": "12345",
    "created_at": "2017-01-05T08:10:36.000Z",
    "updated_at": "2017-01-05T08:10:36.000Z",
    "is_active": true
  },
  {
    "id": 14,
    "first_name": "Nifras",
    "last_name": "nifras",
    "email": "dfjndjf@dffjnd.dfjn",
    "contact_number": "djfndj",
    "user_name": "464555",
    "password": "fddfdf",
    "created_at": "2017-01-05T08:33:39.000Z",
    "updated_at": "2017-01-05T08:33:39.000Z",
    "is_active": true
  }
]

我有另一个名为roles_users的has_many关系表。 (此表包含用户角色的信息。)

table : roles_users
+---------+---------+
| role_id | user_id |
+---------+---------+
|       1 |      13 |
|       1 |      14 |
|       2 |      13 |
|       2 |      14 |
|       3 |      14 |
+---------+---------+

table : roles
+----+-----------+
| id | role_name |   
+----+-----------+
|  1 | admin     | 
|  2 | user      |
|  3 | temp_user |
+----+-----------+

现在我需要将此信息添加到以前的User.all记录中。如何填充相同的方法。

我的预期结果是

[
  {
    "id": 13,
    "first_name": "Gunapala",
    "last_name": "Ratmalana",
    "email": "guna@gmai.com",
    "contact_number": "97866565",
    "user_name": "gunapala",
    "password": "12345",
    "created_at": "2017-01-05T08:10:36.000Z",
    "updated_at": "2017-01-05T08:10:36.000Z",
    "is_active": true,
    "roles": [ "admin", "user" ]
  },
  {
    "id": 14,
    "first_name": "Nifras",
    "last_name": "nifras",
    "email": "dfjndjf@dffjnd.dfjn",
    "contact_number": "djfndj",
    "user_name": "464555",
    "password": "fddfdf",
    "created_at": "2017-01-05T08:33:39.000Z",
    "updated_at": "2017-01-05T08:33:39.000Z",
    "is_active": true,
    "roles": [ "admin", "user","temp_user" ]
  }
]

3 个答案:

答案 0 :(得分:3)

包含与to_json

的关联
def index
  @users = User.all
  if @users.exists?
    render :json => @users.to_json(include: :roles)
  else
    render :json => { "status" => 'S1000', "description" => 'No users are registered' }
  end
end

有关详细信息,请参阅this

答案 1 :(得分:1)

您可以使用jbuilder gem。它允许您通过创建文件app/views/users/index.json.jbuilder来定义任何JSON结构 它几乎是Rails中JSON API的标准解决方案。

答案 2 :(得分:0)

您可以使用https://github.com/rails-api/active_model_serializers

将此添加到Gemfile

gem 'active_model_serializers'

bundle install

之后

将此文件添加到app/serializers/user_serializer.rb(您可以使用用户生成器)

class UserSerializer < ActiveModel::Serializer
  attributes :id,:first_name,:last_name, :email,:contact_number, :user_name, :password, :created_at, :updated_at, :is_active

  has_many: roles
end