Home > Net >  How to manually create new many-to-many entries in Rails
How to manually create new many-to-many entries in Rails

Time:11-18

I have a model Movies and a Model Genres and there is a many to many relationship between them: Movie has_and_belongs_to_many :genres, and Genres has_and_belongs_to_many :movies There of course is a join table:

  create_table "genres_movies", id: false, charset: "utf8mb4", force: :cascade do |t|
    t.bigint "genre_id", null: false
    t.bigint "movie_id", null: false
    t.index ["genre_id", "movie_id"], name: "index_genres_movies_on_genre_id_and_movie_id"
    t.index ["movie_id", "genre_id"], name: "index_genres_movies_on_movie_id_and_genre_id"
  end

I now have a method where I select genres based on some routines and then I want to manually assign these genres to a movie. The following does not work:

new_movie_params[:genre_ids] = genre_array
movie.update(new_movie_params)

I get the following error:

ActiveRecord::RecordNotFound (Couldn't find all Genres with 'id': (, ) (found 0 results, but was looking for 2). Couldn't find Genres with ids , .):

I think that I somehow need to update the join table manually - I have the movie ID and the genre IDs - but I don't know how to do that?

CodePudding user response:

Worked perfectly when ensuring that genre_array actually contains IDs (valid ones) :)

  • Related