Skip to content

Instantly share code, notes, and snippets.

@willviles
Last active March 8, 2017 17:19
Show Gist options
  • Save willviles/001e2a998a8f0c64862ab32e7082cebb to your computer and use it in GitHub Desktop.
Save willviles/001e2a998a8f0c64862ab32e7082cebb to your computer and use it in GitHub Desktop.
Lux - Multiple belongs_to associations from same model
// app/models/image.js
import { Model } from 'lux-framework';
class Image extends Model {
static hasMany = {
avatars: {
model: 'image',
inverse: 'avatar' // also attempted setting `foreignKey: 'avatar_id`
},
coverImages: {
model: 'image',
inverse: 'coverImage' // also attempted setting `foreignKey: 'image_id`
}
}
}
export default Image;
// app/models/user.js
import { Model } from 'lux-framework';
class User extends Model {
static belongsTo = {
avatar: {
model: 'image',
inverse: 'avatars'
},
coverImage: {
model: 'image',
inverse: 'coverImages'
}
};
}
export default User;
// app/serializers/users.js
import { Serializer } from 'lux-framework';
class UsersSerializer extends Serializer {
attributes = [
'foo',
'bar'
];
hasOne = [
'avatar',
'image'
];
}
export default UsersSerializer;
SELECT
"users"."id" AS "id",
"users"."name" AS "name",
"users"."email" AS "email",
"users"."avatar_id" AS "avatar_id",
"users"."cover_image_id" AS "cover_image_id"
FROM
"users"
LEFT OUTER JOIN
"images"
ON "users"."avatar_id" = "avatar_id"
LEFT OUTER JOIN
"images"
ON "users"."cover_image_id" = "cover_image_id"
ORDER BY
USERS.CREATED_AT ASC,
USERS.ID ASC LIMIT 25
{
"data": [
{
"id": "1",
"type": "users",
"attributes": {
"foo": true,
"bar": false
},
"relationships": {
"avatar": {
"data": {
"id": "1",
"type": "images"
},
"links": {
"self": "http://localhost:4000/images/1"
}
},
"cover-image": {
"data": null
}
},
"links": {
"self": "http://localhost:4000/users/1"
}
}
]
}
class User < ActiveRecord::Base
belongs_to :avatar, :class_name => 'Image', :foreign_key => 'avatar_id'
belongs_to :cover_image, :class_name => 'Image', :foreign_key => 'cover_image_id'
end
class Image < ActiveRecord::Base
has_many :avatars, :foreign_key => 'avatar_id'
has_many :cover_images, :foreign_key => 'cover_image_id'
end
@willviles
Copy link
Author

willviles commented Mar 6, 2017

Simply trying to set avatar and coverImage on a user, inheriting from the same image model.

What I'm finding is that the first SQL query (whichever is defined first - in this case avatar), is returned. However, the second SQL query (in this case, coverImage) isn't queried.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment