VegaStudios
VegaStudios

Reputation: 324

Rails Fetching group_id From Another Table

In the User model, I have an archive! method that is called when a User is destroyed.

A User has many User Groups which should be stored in a new ArchivedUserGroup table when a User is destroyed.

The ArchivedUser is successfully created, but I am having trouble fetching the Users' group_id from the UserGroup table.

      ArchivedUserGroup.create(
        user_id: self.id, 
        group_id: UserGroup.where(:user_id => self.id).pluck(:group_id).to_set
      )

Thanks for anyone that has helped me, I am just getting started with Rails and working with a rather complex codebase.

Upvotes: 0

Views: 27

Answers (1)

max pleaner
max pleaner

Reputation: 26778

Since there are many UserGroup records for each user and an ArchivedUserGroup has the same attributes as a regular UserGroup (user_id, group_id), I think you should be created an ArchivedUserGroup for each of the users UserGroup records and not just one. You're trying to pass a set (like an array) to the group_id column. Although you haven't shown your schema, probably group_id is an integer since it's a foreign key, so there's a data type mismatch. Instead you could do this:

UserGroup.where(user_id: self.id).each do |user_group|
  ArchivedUserGroup.create(
    user_id: self.id,
    group_id: user_group.group_id
  )
end

In case some users have a large number of user groups, this may be slow because there's a DB call (create) happening in an iteration. This is known as an N+1 query and the way around it in this case would be to use a bulk insert, either via raw SQL or something like the bulk_insert gem.

Upvotes: 1

Related Questions