In my database, I am tracking articles and images. Every article has three images with predefined sizes. In pure SQL, table ‘articles’ would have three foreign keys: ‘big_image_id’, ‘medium_image_id’, and ‘small_image_id’.
Is there a way of achieving this with Ecto? I am trying it with belongs_to, has_one and foreign_key, but I get “field/association is already set on schema”.
I know that I could use has_many and use an intermediate table, but I don’t need this complication.
You’ll want to use belongs_to in the articles table and has_one in the images table. The relationship setup you’re describing should work fine, so it’s likely an issue with the actual code. Want to share that?
But reverse association is clearly hard. An image has what? One big article? many articles? one big, one medium, one small articles? It’s hard to tell.
It’s really strange to link articles and images like this.
Another way would be to leave article untouched, and add article_id to image… and add an image type. This way it would be easy to say an article has many images, and use filter on image type to retrieve big, medium, small images.
I would use a “has many through” association. The association table would have an extra column for size (big, medium, small). Convenience functions could then select each specific size.
The advantage of this approach is that you don’t have to use a foreign key for image type. That doesn’t really make much sense.
Just be careful that where in the association handled at compile time, so you can’t pass to it the same things you would pass to the Ecto query where. But in this case, it should be just fine.
See the Filtering Associations section in the has_many Ecto docs.