Marco Song Marco Song - 3 months ago 13
Ruby Question

Rails: can not insert element to array

Model

Material
User
Materials_Users(Join table)


In console, when I try
material.user_ids = [1,2]
, it works well. But when I try to insert element one by one, like
material.user_ids << 3
, it does not work, the array turn to empty and nothing is inserted into the array.

How to solve this problem?

Answer

This is because the shovel method only works for objects. Do this instead.

material.users << user

Read here for other ways of adding associations - http://edgeguides.rubyonrails.org/association_basics.html#has-many-association-reference

Comments