Confuse about ecto relationship

Hi all
I have following schemas:

  schema "countries" do

    belongs_to :lang, LanguageCode, foreign_key: :code
    field :text, :string

    timestamps

  end

  schema "languages_code" do

    has_one :code, Country, foreign_key: :lang
    field :text, :string

    timestamps
  end

My question is, when I am going to create the third table that should belongs to LanguageCode too:
schema “table3” do

  belongs_to :coun, CountryCode, foreign_key: :alpha2
  field :text, :string

  timestamps

end

how do I have to modify the languages_code schema?

Thanks

Hi @kostonstyle
You could do it the same way you did above.
add has_one to the language_code table. And add belongs_to to the third table.

I am seeing you are using has_one here. I am seeing that you have same column name in both or three tables. I think you can actually merge them all in a single table and mapped to a single schema by prefixing column names to make them distinct. Given that both or three of tables’ colums will be created at once and destroyed as once, if not putting them on seperate tables are the right way to go.

1 Like