【问题标题】:Rails NoMethodError: undefined method `includes' for #<User:0x007f62dbbe62f8>Rails NoMethodError:#<User:0x007f62dbbe62f8> 的未定义方法“包含”
【发布时间】:2017-06-28 22:10:10
【问题描述】:

我在我的 Rails 5 应用程序中使用 active_model_serializers gem。我在/app/seralizers、user_serializer.rb、sector_serializer.rb 和slot_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 的那一行出现错误,我不知道为什么。

感谢任何帮助。谢谢!

【问题讨论】:

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


    【解决方案1】:

    改变

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

    到

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

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

    【讨论】:

    • 完美。非常感谢乌苏斯
    • 我的荣幸先生 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多