Creating multiple records, giving an array of params

Viewed 21

For example, I have a model Hobby. And I have a User model, and user has many hobbies. Hobby also has many users. And I have a linking table UserHobby (belongs to user, belongs to hobby).

Some user registers on a site, picks some hobbies, and then saves this list. Technically creates an array of records. So on my backend part I have to do something like this:

UserHobby.create( user: user, hobby: params[:hobbies]), where :hobbies is an array. But it doesn't work this way.

Is there a way to do this without using something like params[:hobbies].map{ |hobby| UserHobby.create( user: user, hobby: hobby) } ?

1 Answers

The map is fine, but when creating associations use association methods.

params[:hobbies] is a param coming from a form, so presumably it contains an Array of Hobby IDs (perhaps better as params[:hobby_ids]). Since these Hobbies already exist in the database, we can simply append them to the user's list of hobbies. This will insert the necessary rows in the join table.

user.hobbies << Hobbies.where(id: params[:hobbies])

user.hobbies is cached and Rails will only check the database once. If you do UserHobby.create!(user: user, hobby: hobby) then user.hobbies will be out of date. If you update user.hobbies directly then user.hobbies will be updated.

Related