JG3 JG3 - 2 months ago 16
Ruby Question

Merging parameters rails

in my rails app, a user can select other users they'd like to join a 'party' with. I'm trying to merge the current user's ID with those that the user has selected. This is one way i've tried:

def party_params
params.require(:party).permit(:length, :game_id, user_ids: []).merge("user_ids" => ["user_ids"] + [current_user.id])
end


This comes back with :


Couldn't find all Users with 'id': (0, 17) (found 1 results, but was
looking for 2)


Doing
.merge(:user_ids => [current_user.id])
instead results in the party only being created with the current user and removing all the selected users.

I've also tried moving the .merge to a function and calling it on new, but that doesn't seem to work either.

In my models a party
has_and_belongs_to_many :users
and likewise a user
has_and_belongs_to_many :parties


Any help appreciated!
Thanks.

Answer

I would write it like this:

def party_params
  params.require(:party).permit(:length, :game_id, user_ids: []).tap do |p|
    p[:user_ids] << current_user.id
  end
end
Comments