Very new to rails. I'm building a simple app to take a group of users and randomly assign teams of 5. Everything is working fine except for a "Clear Teams" link in one of my views. The links is supposed to update the team and team2 attributes of each user to be 0. When I click the link, the update doesn't happen, and each user's team and team2 attribute remain unchanged.
Model:
def self.clear_teams
pt = User.all
pt.each do |v|
if v.team != 0
v.update_attribute(:team, 0)
end
if v.team2 != 0
v.update_attribute(:team2, 0)
end
end
end
Calling User.clear_teams in the console works, so I'm thinking I have a routing issue.
Controller:
def clear
@users = User.all
@users.clear_teams
redirect_to action: :index
end
View:
<%= link_to "Clear Teams", clear_users_path, method: :patch, class: 'col-xs-12 btn-primary clear', data: { confirm: 'Are you sure you want to clear the teams?' } %>
routes.rb:
patch 'users' => 'users#clear', as: :clear_users
Routes:
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
user DELETE /users/:id(.:format) users#destroy
DELETE /users(.:format) users#destroy_all
PATCH /users(.:format) users#randomize
clear_users PATCH /users(.:format) users#clear
root GET / users#index
You have defined a class method
clear_teams
. You need to be calling it likeUser.clear_teams
, not like an instance method - which is what you currently have in yourclear
action. See article on difference @ http://www.railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/