为什么我的Rails 5应用程序每个记录打印两次?

时间:2017-06-25 09:17:09

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

这是一个rails管理应用程序,同时也是一个API。当我调用myroot / api / v1 / users时,我会得到两次记录。

这是我的用户模型类:

class User < ActiveRecord::Base
  devise :database_authenticatable, :recoverable,
         :trackable, :validatable, :registerable,
         :omniauthable

  include DeviseTokenAuth::Concerns::User
  has_many :records
end

这是我的Record模型类:

class Record < ApplicationRecord
  belongs_to :user
  has_attached_file :audio,
                      :url => "/assets/:class/:id/:attachment/:style.:extension",
                      :path => ":rails_root/public/assets/records/:id/:style/:basename.:extension"
  validates_attachment_presence :audio
  validates_attachment_size :audio, :less_than => 3.megabytes
  validates_attachment_content_type :audio, :content_type => [ 'audio/mpeg',  'audio/mp3' ]

end

这是我的控制器用户类:

class Api::UsersController < Api::ApiController
  before_action :set_user, only: [:show, :edit, :update, :destroy]

  def index
      # users = User.all
      # render json: users.to_json(except: [:id, :user_id, :email, :nickname])
      users = User.joins(:records)
       render json: users.to_json(only: [:id, :user_id, :email, :nickname], 
       include: {records: {only: [:record_id, :geolocation, :audio_file_name, :audio_content_type]}})
  end

  def show
      user = User.find(params[:id])
      render json: user.to_json(except: [:id, :user_id, :email, :nickname])
  end
end 

这是JSON的结果:

[
    {
        "id": 4,
        "nickname": null,
        "email": "ricardope@gmail.com",
        "records": [
            {
                "geolocation": "-12.0858307,-76.9795114,17",
                "audio_file_name": "StarCraft_2_-_Probe_Quotes.mp3",
                "audio_content_type": "audio/mpeg"
            },
            {
                "geolocation": "-12.0858307,-76.9795114,17",
                "audio_file_name": "StarCraft_2_-_Selendis_Quotes.mp3",
                "audio_content_type": "audio/mpeg"
            }
        ]
    },
    {
        "id": 4,
        "nickname": null,
        "email": "ricardope@gmail.com",
        "records": [
            {
                "geolocation": "-12.0858307,-76.9795114,17",
                "audio_file_name": "StarCraft_2_-_Probe_Quotes.mp3",
                "audio_content_type": "audio/mpeg"
            },
            {
                "geolocation": "-12.0858307,-76.9795114,17",
                "audio_file_name": "StarCraft_2_-_Selendis_Quotes.mp3",
                "audio_content_type": "audio/mpeg"
            }
        ]
    },
    {
        "id": 6,
        "nickname": null,
        "email": "gabriela@gmail.com",
        "records": [
            {
                "geolocation": "-12.0858307,-76.9795114,17",
                "audio_file_name": "StarCraft_2_-_Carrier_Quotes.mp3",
                "audio_content_type": "audio/mpeg"
            },
            {
                "geolocation": "-12.0858307,-76.9795114,17",
                "audio_file_name": "StarCraft_2_-_Zealot_Quotes.mp3",
                "audio_content_type": "audio/mpeg"
            }
        ]
    },
    {
        "id": 6,
        "nickname": null,
        "email": "gabriela@gmail.com",
        "records": [
            {
                "geolocation": "-12.0858307,-76.9795114,17",
                "audio_file_name": "StarCraft_2_-_Carrier_Quotes.mp3",
                "audio_content_type": "audio/mpeg"
            },
            {
                "geolocation": "-12.0858307,-76.9795114,17",
                "audio_file_name": "StarCraft_2_-_Zealot_Quotes.mp3",
                "audio_content_type": "audio/mpeg"
            }
        ]
    }
]

这是日志:

Processing by Api::UsersController#index as */*
  User Load (0.2ms)  SELECT `users`.* FROM `users` INNER JOIN `records` ON `records`.`user_id` = `users`.`id`
  Record Load (0.2ms)  SELECT `records`.* FROM `records` WHERE `records`.`user_id` = 4
  CACHE Record Load (0.0ms)  SELECT `records`.* FROM `records` WHERE `records`.`user_id` = 4  [["user_id", 4]]
  Record Load (0.3ms)  SELECT `records`.* FROM `records` WHERE `records`.`user_id` = 6
  CACHE Record Load (0.0ms)  SELECT `records`.* FROM `records` WHERE `records`.`user_id` = 6  [["user_id", 6]]
Completed 200 OK in 97ms (Views: 0.3ms | ActiveRecord: 3.4ms)

2 个答案:

答案 0 :(得分:1)

正如Pavan所说,我改变了CMDusers = User.joins(:records) for users = User.all并且有效。

答案 1 :(得分:1)

<强>解释

users = User.joins(:records)

以上活动记录查询会触发INNER JOINusers表之间的records查询。这意味着它将从两个表中获取所有记录,因为没有where子句。

输出将是来自users表或records表的总行数,其中一行最高。

这就是你获得users表的重复记录的原因。

此行User.all仅为您提供users表的记录,如果您还想要records表格行,则必须遵循以下内容。

现在,下面的行给出了users表的结果以及来自records

的所有相关记录
User.includes(:records)

您将看不到users表中的重复记录。 因为它会在2个表上进行查询,其中一个在users上,另一个在records

希望你能通过这篇文章得到更多的澄清。