One to Many relationships in Ecto

I’m currently building an app in Phoenix, but I’m having trouble wrapping my head around a simple relationship.

I have a User model, and that user has a Type. AFAIK, I should have a user table, with a field type_id, and a type table that has only it’s own keys.

Simple, right? I did something like:

schema "users" do
    has_one :type, MyApp.Type
end

schema "types" do
    belongs_to :users, MyApp.Users
end

But, the problem is the belongs_to macro generates a user_id field on the types schema, and that’s not how I see things.

Now, I could do something like this (and I have done):

schema "users" do
    belongs_to :type, MyApp.Type
end

schema "types" do
    has_many :users, MyApp.User
end

That’s not necessarily wrong. We could think that, since each user has a type, it belongs to that type.
But, if we say every user has a type, we could argument that a type belongs to a user.

Am I doing something wrong? This second version works fine, I just want to make sure I have the right relationships on my application.

Thanks!

1 Like

The second one looks fine to me. Have a look here: http://learningwithjb.com/posts/has-many-relationship

I haven’t actually learned Ecto/Phoenix yet, but in Rails at least, a has_many association indicates a one-to-many connection and you’ll often find this on the other side of a belongs_to association. (Zero or more of the other.)

I was having the same problem. So I built a little demo of has_many …

has_many_blog on github

Eventually, I want to add an example of using many_to_many.
But I don’t have that figured out yet.

Hope this helps.