vendredi 25 mars 2016

Associate two already existing objects using Has And Belongs To Many

I'm making an App in Rails to show anime, these animes has and belongs to many languages, so I made a HABTM association:

class Anime < ActiveRecord::Base
  has_and_belongs_to_many :languages
end

class Language < ActiveRecord::Base
  has_and_belongs_to_many :animes
end

Now I don't know how can I make associations between them, I've created many Languages' records to use them, for example, Language with ID 1 is English, Language with ID 2 is Spanish, etc... And I want to just make the associations between an anime and a language, ie, if I want to say that the Anime with ID 1 it's available in Spanish only, then in the table animes_languages I want to create the record with values anime_id: 1 and language_id: 2 and nothing more, but I belive that if I execute the command Anime.find(1).languages.create it will not use an already existing language, it will create a new language, but the only thing I want is to make associations between already existing animes with already existing languages, so, How can I do this? Should I make a model for the table animes_language?

It's confusing for me cause when I created that table as specified here enter link description here, I created the table without ID, it only have the fields anime_id and language_id.

Aucun commentaire:

Enregistrer un commentaire