Reputation: 1712
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.
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'
Upvotes: 2
Views: 6942
Reputation: 7517
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.
Upvotes: 0
Reputation: 33420
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
Upvotes: 3
Reputation: 323
Not sure if this is the problem but your setting a variable to something that youve destroyed
Upvotes: 0