【发布时间】:2015-06-12 21:21:07
【问题描述】:
对 Rails 很陌生。我正在构建一个简单的应用程序来获取一组用户并随机分配 5 人的团队。除了我的一个视图中的“清除团队”链接之外,一切都运行良好。链接应该将每个用户的team和team2属性更新为0。当我点击链接时,更新不会发生,每个用户的team和team2属性保持不变。
型号:
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
在控制台中调用 User.clear_teams 有效,所以我认为我遇到了路由问题。
控制器:
def clear
@users = User.all
@users.clear_teams
redirect_to action: :index
end
查看:
<%= 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
路线:
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
【问题讨论】:
标签: ruby-on-rails routing patch update-attributes