Search code examples
elixirecto

Confuse about ecto relationship


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?


Solution

  • Unless I'm mistaken, what your asking is how to represent the belongs_to relationship on the LanguagesCode model?

    If so then depending on whether or not a Language code can have one or more table3 rows belonging to it, you would do:

     schema "languages_code" do
    
        has_one :code, Country, foreign_key: :lang
    
        #For has_one
        has_one :code, Table3ModuleName, foreign_key: :alpha2
    
        #For has_many
        has_many :code, Table3ModuleName, foreign_key: :alpha2 
    
        field :text, :string
    
        timestamps
      end
    

    You would of course replace, Table3ModuleName with the actual name of the module containing the table3 table schema definition.