对rails很新。我正在构建一个简单的应用程序来接纳一组用户并随机分配5个团队。除了" Clear Teams"在我的一个观点中链接。链接应该将每个用户的团队和team2属性更新为0.当我单击链接时,更新不会发生,并且每个用户的团队和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
答案 0 :(得分:0)
您已经定义了一个类方法clear_teams
。您需要像User.clear_teams
一样调用它,而不是像实例方法一样 - 这是您在clear
操作中的当前操作。请参阅有关差异@ http://www.railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/