2

I have this method in my groups controller.

def remove
  @usergroup = Usergroup.where(group_id: params[:group_id]).destroy
  redirect_to groups_path
end

And

<%= link_to 'Remove', { controller: "groups", action: "remove" },
    group_id: @group.id, data: { confirm: 'Are you sure?' } %>

When I click remove and confirm the removal, I get this error.

enter image description here

I am a bit confused because the id of the group is 6 and it should be. For the group I am trying to remove somebody from. Why would it be giving me a no arguments error for this?

This is a route I have set. I believe this is the issue. get 'groups/remove/:id', to: 'groups#remove'

0

4 Answers 4

3

As you're using where, and it returns a Model::ActiveRecord_Relation, then you need to "identify" the object you want to destroy, that's, accessing the singular element, you can do it by accessing a specific element in the result, like:

Usergroup.where('group_id = ?', params[:group_id]).first.destroy

Or to use destroy_all, which would take all the objects within that result and destroy all of them:

Usergroup.where('group_id = ?', params[:group_id]).destroy_all
Sign up to request clarification or add additional context in comments.

5 Comments

After trying your method I seem to be getting this error: undefined method destroy' for nil:NilClass`
So your query using where has an empty result.
.where().first => .find_by
Please see updated question. I believe this has something to do with the route.
You're using params[:group_id], but your route and your params say id, try instead using id in both cases @TrentonTyler.
0

Not sure if this is the problem but your setting a variable to something that youve destroyed

Comments

0

Your params are id =6 not group_id =6

2 Comments

This can be added as a comment Dave.
Yeah sorry my phone is flidding out.
0

I think its because of your use of where, you are trying to call destroy on a list of objects because when you call ActiveRecord .where it returns a list even if there is only one. You should try to do it like this instead:

@group = Usergroup.find_by(group_id: params[:group_id])
if @group
  @group.destroy
...

and make your link_to like this:

<%= link_to 'Remove', name_of_path_here_path(group_id: @group.id), confirm: 'Are you sure?', method: :delete %>

Also, remember that you could use the Restful routes pattern commonly used in Rails: routes.rb (ex: resources :usergroups). You can also alias routes with the as: :name_of_route_here. To double check your routes you can open up terminal and run bundle exec rake routes and on the left column of the routes is the name of the route helper. Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.