使用Typescript未正确设置与主干关联的Model 1:M集合
我使用1:M与Backbone.AssociatedModels的关系,以便将配置文件模型添加到公会模型中(因为配置文件是公会的成员) 当一个用户创建一个新的公会时,我希望与该用户对应的模型被添加到公会的“用户”属性中。 因此,在我看来,我调用了在我的模型中定义的createGuild函数,该函数将登录用户的配置文件的模型作为参数 然后我试着用配置文件设置我的公会的“用户”属性。但是,当我这样做时,主干关联确实创建了一个概要文件集合,但它似乎是空的:使用Typescript未正确设置与主干关联的Model 1:M集合,typescript,backbone.js,backbone-model,backbone-associations,Typescript,Backbone.js,Backbone Model,Backbone Associations,我使用1:M与Backbone.AssociatedModels的关系,以便将配置文件模型添加到公会模型中(因为配置文件是公会的成员) 当一个用户创建一个新的公会时,我希望与该用户对应的模型被添加到公会的“用户”属性中。 因此,在我看来,我调用了在我的模型中定义的createGuild函数,该函数将登录用户的配置文件的模型作为参数 然后我试着用配置文件设置我的公会的“用户”属性。但是,当我这样做时,主干关联确实创建了一个概要文件集合,但它似乎是空的: Profiles {length: 1, m
Profiles {length: 1, models: Array(1), _byId: {…}, parents: Array(1), model: ƒ, …}
length: 0
model: ƒ Profile(options)
models: []
parents: [Guild]
_byId: {}
...
当我这样做的时候
console.log(this.get("users[0]"));
控制台告诉我这是未定义的
我的公会模式如下:
export default class Guild extends Backbone.AssociatedModel {
constructor(options?: any) {
super(options);
this.relations = [
{
type: Backbone.Many,
key: "users",
collectionType: Profiles,
relatedModel: Profile,
},
];
}
urlRoot = () => "http://localhost:3000/guilds";
sync(method: string, model: Guild, options: JQueryAjaxSettings): any {
//This is to be able to upload a picture
if (method == "create") {
var formData = new FormData();
_.each(model.attributes, function (value, key) {
formData.append(key, value);
});
_.defaults(options || (options = {}), {
data: formData,
processData: false,
contentType: false,
});
}
return Backbone.sync.call(this, method, model, options);
}
createGuild(
attrs: CreatableGuildArgs,
//Here the function is passed the profile than I need from my View
profile: Backbone.AssociatedModel,
error: (errors: string[]) => void,
success: () => void
) {
this.set(attrs);
//This is how I set my users attribute
this.set({users: profile});
console.log(this.get("users"));
this.save(
{},
{
url: this.urlRoot(),
success: () => success(),
error: (_, jqxhr) => {
error(this.mapServerErrors(jqxhr?.responseJSON));
},
}
);
}
....
}
我的个人资料模型如下:
export default class Profile extends Backbone.AssociatedModel {
constructor(options?: any) {
super(options);
this.relations = [
{
type: Backbone.One,
key: "guild",
relatedModel: Guild,
},
];
}
urlRoot = () => "http://localhost:3000/user";
...
对于API,我使用的是rails,我的模型设置如下:
class Guild < ApplicationRecord
has_one_attached :img
has_many :users
...
end
class User < ApplicationRecord
has_one_attached :avatar
belongs_to :guild, optional: true
....
end
- create.json.jbuilder文件
this.set({users: profile});
与
但是set()不起作用,因为用户是未定义的
我觉得这个问题是因为我的“users”属性没有正确初始化,但我似乎无法这样做。我使用的是typescript,所以我很难复制文档中描述的内容
有人知道我如何获得一个包含我试图设置的配置文件的正确配置文件集合吗
谢谢你的帮助
json.partial! "guilds/guild", guild: @guild
this.set({users: profile});
this.get('users').at(0).set(profile);