Zac*_*iro 3 ruby ruby-on-rails active-model-serializers ruby-on-rails-5
我active_model_serializers在我的 Rails 5 应用程序中使用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
Run Code Online (Sandbox Code Playgroud)
在我的控制器代码中,我有:
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
Run Code Online (Sandbox Code Playgroud)
我的服务器在我执行的那一行抛出错误,.includes我不知道为什么。
任何帮助表示赞赏。谢谢!
改变
@user = User.find_by_id(params[:user_id]).includes(:sectors, :slots)
Run Code Online (Sandbox Code Playgroud)
到
@user = User.includes(:sectors, :slots).find_by_id(params[:user_id])
Run Code Online (Sandbox Code Playgroud)
重点是您必须调用includes一个类(从ActiveRecord::Base/继承ApplicationRecord),而不是单个用户对象。
| 归档时间: |
|
| 查看次数: |
2031 次 |
| 最近记录: |