Ruby on rails 在RubyonRails中,当使用has_和_-belies_-to关系时,序列化数据的最佳方法是什么
我有一个在Rails 5中无法解决的问题 我试图在项目管理工具的状态代码中建立has_和_-belish_-to_许多关系。我把它叫做“position”,因为“status”在ruby中使用 这是控制器:Ruby on rails 在RubyonRails中,当使用has_和_-belies_-to关系时,序列化数据的最佳方法是什么,ruby-on-rails,relationship,Ruby On Rails,Relationship,我有一个在Rails 5中无法解决的问题 我试图在项目管理工具的状态代码中建立has_和_-belish_-to_许多关系。我把它叫做“position”,因为“status”在ruby中使用 这是控制器: class ProjectsController < ApplicationController before_action :set_project, only: [:show, :update, :destroy] # GET /projects def index
class ProjectsController < ApplicationController
before_action :set_project, only: [:show, :update, :destroy]
# GET /projects
def index
@projects = Project.all
render json: @projects
end
private
# Use callbacks to share common setup or constraints between actions.
def set_project
@project = Project.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def project_params
params.require(:project).permit(:name, :description, :complete, :client_id)
end
end
class ProjectsController
这是我的模型
职位模型
class Position < ApplicationRecord
has_and_belongs_to_many :project, join_table: "projects_positions", foreign_key: "brief_id"
has_and_belongs_to_many :brief, join_table: "briefs_positions", foreign_key: "epic_id"
has_and_belongs_to_many :feature, join_table: "features_positions", foreign_key: "story_id"
has_and_belongs_to_many :epic, join_table: "epics_positions", foreign_key: "story_id"
has_and_belongs_to_many :story, join_table: "stories_positions", foreign_key: "story_id"
end
enter code here
class Position
这是相应的模型
class Project < ApplicationRecord
belongs_to :client
has_many :briefs
has_many :features
has_many :epics
has_and_belongs_to_many :sector, join_table: "projects_sectors", foreign_key: "project_id"
has_and_belongs_to_many :position, join_table: "projects_positions", foreign_key: "project_id"
end
类项目
所有其他对应的模型都与上面相同,为了节省空间和阅读,我将它们省略,因为下面的错误只对应于这些模型
序列化程序如下所示:
class ProjectSerializer < ActiveModel::Serializer
attributes :id, :name, :description
has_one :client
has_many :sectors
has_many :briefs
has_many :epics
has_many :positions
end
class ProjectSerializer
我正在使用序列化程序中的has\u many来输出has\u和\u-belish\u-to\u-many关系。但是,当我尝试获取所有项目时,会出现一个未定义的方法错误
错误如下
"status": 500,
"error": "Internal Server Error",
"exception": "#<NoMethodError: undefined method `sectors' for # .
“状态”:500,
“错误”:“内部服务器错误”,
“例外”:“#更改为has_和_属于_多个:扇区,您使用的是可能导致冲突的单数版本‘扇区’。更改为has_和_属于_多个:扇区,您使用的是可能导致冲突的单数版本‘扇区’。