我有一个很笨的问题,我有两个模型。
class User < ApplicationRecord
belongs_to :role
end
和
class Role < ApplicationRecord
has_many :user
end
我试图获取用户,并与角色的表进行连接,以获取角色的名称和id,比如说。
"user" : {"name": "json", "role",{"name": "admin", "id": {"name": "admin", "id":1}}。
然而,使用后。
User.includes(:role).all
我只得到了带有 "role_id "值的用户,我也试了一下
User.joins(:role)
也是一样的结果。我一直在看官方文档,在(https:/guides.rubyonrails.orgactive_record_querying.html。),这应该是很直接的,但我不知道我做错了什么。我需要在我的迁移中添加一些东西吗,在我的create_user迁移中我有。
class CreateUsers < ActiveRecord::Migration[6.0]
def change
create_table :users do |t|
t.string :username
t.string :email
t.integer :role_id
end
add_index :users, :email
add_index :users, :username
end
end
和我的create_roles迁移
class CreateRoles < ActiveRecord::Migration[6.0]
def change
create_table :roles do |t|
t.string :name
end
end
end
all
本身并不能返回这样一个自定义数据。你可以使用 as_json
为此。
User.all.as_json(only: :name, include: { role: { only: [:name, :id] } }, root: true)
# User Load (0.5ms) SELECT "users".* FROM "users"
# Role Load (0.6ms) SELECT "roles".* FROM "roles" WHERE "roles"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
# => [{"user"=>{"name"=>"json", "role"=>{"id"=>1, "name"=>"admin"}}}]