Rails NoMethodError:未定义的方法`includes'for#<user:0x007f62dbbe62f8>

时间:2017-06-28 22:10:11

标签: ruby-on-rails ruby ruby-on-rails-5 active-model-serializers

我正在使用我的Rails 5应用中的active_model_serializers gem。我在/app/seralizersuser_serializer.rbsector_serializer.rbslot_serializer.rb中创建了一些序列化文件。

class UserSerializer < ActiveModel::Serializer
    attributes :id, :first_name, :last_name, :email, :phone, :admin, :auth_token, :organization_id

    has_many :sectors
    has_many :slots
    has_many :elements
end

class SectorSerializer < ActiveModel::Serializer
    attributes :id, :user_id, :sector_number, :title

    belongs_to :user
    has_many :slots
    has_many :elements
end

class SlotSerializer < ActiveModel::Serializer
    attributes :id, :user_id, :sector_id, :sector_number, :title, :slot_number

    belongs_to :user
    belongs_to :sector
    has_many :elements
end

在我的控制器代码中,我有:

class Api::V1::UsersController < API::V1::BaseController
  respond_to :json

  def sky
      @user = User.find_by_id(params[:user_id]).includes(:sectors, :slots)

      if @user
        render json: @user
      else
          raise "Unable to get Sky"
      end
  end
end

我的服务器在我执行.includes的行中抛出错误,我无法弄清楚原因。

感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:3)

更改

@user = User.find_by_id(params[:user_id]).includes(:sectors, :slots)

@user = User.includes(:sectors, :slots).find_by_id(params[:user_id])

要点是你必须在一个类(继承自includes / ActiveRecord::Base)上调用ApplicationRecord,而不是单个用户对象。