【问题标题】:Rails 4 patch request does not update attributesRails 4补丁请求不更新属性
【发布时间】: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


    【解决方案1】:

    你已经定义了一个类方法clear_teams。您需要像 User.clear_teams 一样调用它,而不是像实例方法一样 - 这是您当前在 clear 操作中拥有的。见差异文章@http://www.railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-10
      • 1970-01-01
      • 2020-04-28
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2014-04-20
      • 2013-11-16
      相关资源
      最近更新 更多