为User创建销毁操作

时间:2014-10-17 14:53:20

标签: ruby-on-rails

我正在为用户添加销毁操作。单击删除用户链接时,出现Mysql2::Error at /users/test Unknown column 'users.user_id' in 'where clause'错误。它指向@user = User.find_by(username: params[:id]).destroy行。

也许问题是params向用户显示他们的用户名,与他们的id相反。因此,在我的参数中,它试图删除用户/users/test,而销毁操作可能会期望它为/users/3

用户控制器:

  def settings
    @user = User.find(params[:id])
    render layout: 'new_application'
  end

  def new
    @user = User.new
    render layout: 'new_application'
  end

     def show
        @user = User.find_by(username: params[:id])
      end

      def edit
        @user = User.find_by(username: params[:id])
      end

  def profile
    @profile = User.profile
    @user = User.find_by(username: params[:id])
  end


  def destroy
    @user = User.find_by(username: params[:id]).destroy
    @user.destroy
    flash[:success] = "User deleted."
    redirect_to :back
  end

      def index
        @user = current_user
        @users = @user.present? ? User.where('id != ?',@user.id) : User.all
        render layout: 'new_application'    
      end

查看:

<% @users.each do |user| %>
    <li>
        <%= link_to user.username, user %>

            | <%= link_to "delete", user, method: :delete,
                                          data: { confirm: "You sure?"} %>
        </li>
        <% end %>

错误日志:

Started DELETE "/users/test" for 127.0.0.1 at 2014-10-23 11:07:08 -0400
Processing by UsersController#destroy as HTML
  Parameters: {"authenticity_token"=>"GfWT4qeWAKLkTs5NNioiACVSy03vHsOYb8eS7D358bw=", "id"=>"test"}
  User Load (197.0ms)  SELECT `users`.* FROM `users` WHERE `users`.`auth_token` = '4zieBdE5JIZZ5v63Weio-g' LIMIT 1
  User Load (0.4ms)  SELECT `users`.* FROM `users` WHERE `users`.`username` = 'test' LIMIT 1
   (30.8ms)  BEGIN
  Receipt Load (61.3ms)  SELECT `receipts`.* FROM `receipts` WHERE `receipts`.`receiver_id` = 3 AND `receipts`.`receiver_type` = 'User' ORDER BY created_at DESC
  Letsgo Load (15.2ms)  SELECT `letsgos`.* FROM `letsgos` WHERE `letsgos`.`user_id` = 3 ORDER BY created_at DESC
  User Load (8.3ms)  SELECT `users`.* FROM `users` WHERE `users`.`user_id` = 3
Mysql2::Error: Unknown column 'users.user_id' in 'where clause': SELECT `users`.* FROM `users`  WHERE `users`.`user_id` = 3
   (1.1ms)  ROLLBACK
Completed 500 Internal Server Error in 465ms

Mysql2::Error - Unknown column 'users.user_id' in 'where clause':
  activerecord (4.0.0.rc1) lib/active_record/connection_adapters/abstract_mysql_adapter.rb:286:in `block in execute'
  activerecord (4.0.0.rc1) lib/active_record/connection_adapters/abstract_adapter.rb:425:in `block in log'
  activesupport (4.0.0.rc1) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  activerecord (4.0.0.rc1) lib/active_record/connection_adapters/abstract_adapter.rb:420:in `log'
  activerecord (4.0.0.rc1) lib/active_record/connection_adapters/abstract_mysql_adapter.rb:286:in `execute'
  activerecord (4.0.0.rc1) lib/active_record/connection_adapters/mysql2_adapter.rb:220:in `execute'
  activerecord (4.0.0.rc1) lib/active_record/connection_adapters/mysql2_adapter.rb:224:in `exec_query'
  activerecord (4.0.0.rc1) lib/active_record/connection_adapters/mysql2_adapter.rb:233:in `select'
  activerecord (4.0.0.rc1) lib/active_record/connection_adapters/abstract/database_statements.rb:24:in `select_all'
  activerecord (4.0.0.rc1) lib/active_record/connection_adapters/abstract/query_cache.rb:61:in `block in select_all'
  activerecord (4.0.0.rc1) lib/active_record/connection_adapters/abstract/query_cache.rb:76:in `cache_sql'
  activerecord (4.0.0.rc1) lib/active_record/connection_adapters/abstract/query_cache.rb:61:in `select_all'
  activerecord (4.0.0.rc1) lib/active_record/querying.rb:36:in `find_by_sql'
  activerecord (4.0.0.rc1) lib/active_record/relation.rb:561:in `exec_queries'
  activerecord (4.0.0.rc1) lib/active_record/relation.rb:447:in `load'
  activerecord (4.0.0.rc1) lib/active_record/relation.rb:196:in `to_a'
  activerecord (4.0.0.rc1) lib/active_record/associations/collection_association.rb:415:in `find_target'
  activerecord (4.0.0.rc1) lib/active_record/associations/collection_association.rb:358:in `load_target'
  activerecord (4.0.0.rc1) lib/active_record/associations/has_many_association.rb:25:in `handle_dependency'
  activerecord (4.0.0.rc1) lib/active_record/associations/builder/association.rb:97:in `has_many_dependent_for_users'
  activesupport (4.0.0.rc1) lib/active_support/callbacks.rb:416:in `_run__3511049082865519219__destroy__callbacks'
  activesupport (4.0.0.rc1) lib/active_support/callbacks.rb:80:in `run_callbacks'
  activerecord (4.0.0.rc1) lib/active_record/callbacks.rb:289:in `destroy'
  activerecord (4.0.0.rc1) lib/active_record/transactions.rb:265:in `block in destroy'
  activerecord (4.0.0.rc1) lib/active_record/transactions.rb:326:in `block in with_transaction_returning_status'
  activerecord (4.0.0.rc1) lib/active_record/connection_adapters/abstract/database_statements.rb:202:in `block in transaction'
  activerecord (4.0.0.rc1) lib/active_record/connection_adapters/abstract/database_statements.rb:210:in `within_new_transaction'
  activerecord (4.0.0.rc1) lib/active_record/connection_adapters/abstract/database_statements.rb:202:in `transaction'
  activerecord (4.0.0.rc1) lib/active_record/transactions.rb:209:in `transaction'
  activerecord (4.0.0.rc1) lib/active_record/transactions.rb:323:in `with_transaction_returning_status'
  activerecord (4.0.0.rc1) lib/active_record/transactions.rb:265:in `destroy'
  app/controllers/users_controller.rb:55:in `destroy'
  actionpack (4.0.0.rc1) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
  actionpack (4.0.0.rc1) lib/abstract_controller/base.rb:189:in `process_action'
  actionpack (4.0.0.rc1) lib/action_controller/metal/rendering.rb:10:in `process_action'
  actionpack (4.0.0.rc1) lib/abstract_controller/callbacks.rb:18:in `block in process_action'
  activesupport (4.0.0.rc1) lib/active_support/callbacks.rb:403:in `block in _run__1102190075216407520__process_action__callbacks'
  activesupport (4.0.0.rc1) lib/active_support/callbacks.rb:218:in `block in _conditional_callback_around_2324'
  activesupport (4.0.0.rc1) lib/active_support/core_ext/time/zones.rb:45:in `use_zone'
  app/controllers/application_controller.rb:19:in `user_time_zone'
  activesupport (4.0.0.rc1) lib/active_support/callbacks.rb:217:in `_conditional_callback_around_2324'
  activesupport (4.0.0.rc1) lib/active_support/callbacks.rb:402:in `_run__1102190075216407520__process_action__callbacks'
  activesupport (4.0.0.rc1) lib/active_support/callbacks.rb:80:in `run_callbacks'
  actionpack (4.0.0.rc1) lib/abstract_controller/callbacks.rb:17:in `process_action'
  actionpack (4.0.0.rc1) lib/action_controller/metal/rescue.rb:29:in `process_action'
  actionpack (4.0.0.rc1) lib/action_controller/metal/instrumentation.rb:31:in `block in process_action'
  activesupport (4.0.0.rc1) lib/active_support/notifications.rb:159:in `block in instrument'
  activesupport (4.0.0.rc1) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  activesupport (4.0.0.rc1) lib/active_support/notifications.rb:159:in `instrument'
  actionpack (4.0.0.rc1) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
  actionpack (4.0.0.rc1) lib/action_controller/metal/params_wrapper.rb:245:in `process_action'
  activerecord (4.0.0.rc1) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
  actionpack (4.0.0.rc1) lib/abstract_controller/base.rb:136:in `process'
  actionpack (4.0.0.rc1) lib/abstract_controller/rendering.rb:44:in `process'
  actionpack (4.0.0.rc1) lib/action_controller/metal.rb:195:in `dispatch'
  actionpack (4.0.0.rc1) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
  actionpack (4.0.0.rc1) lib/action_controller/metal.rb:231:in `block in action'
  actionpack (4.0.0.rc1) lib/action_dispatch/routing/route_set.rb:80:in `dispatch'
  actionpack (4.0.0.rc1) lib/action_dispatch/routing/route_set.rb:48:in `call'
  actionpack (4.0.0.rc1) lib/action_dispatch/journey/router.rb:71:in `block in call'
  actionpack (4.0.0.rc1) lib/action_dispatch/journey/router.rb:59:in `call'
  actionpack (4.0.0.rc1) lib/action_dispatch/routing/route_set.rb:654:in `call'
  rack (1.5.2) lib/rack/etag.rb:23:in `call'
  rack (1.5.2) lib/rack/conditionalget.rb:35:in `call'
  rack (1.5.2) lib/rack/head.rb:11:in `call'
  actionpack (4.0.0.rc1) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
  actionpack (4.0.0.rc1) lib/action_dispatch/middleware/flash.rb:241:in `call'
  rack (1.5.2) lib/rack/session/abstract/id.rb:225:in `context'
  rack (1.5.2) lib/rack/session/abstract/id.rb:220:in `call'
  actionpack (4.0.0.rc1) lib/action_dispatch/middleware/cookies.rb:486:in `call'
  activerecord (4.0.0.rc1) lib/active_record/query_cache.rb:36:in `call'
  activerecord (4.0.0.rc1) lib/active_record/connection_adapters/abstract/connection_pool.rb:626:in `call'
  actionpack (4.0.0.rc1) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
  activesupport (4.0.0.rc1) lib/active_support/callbacks.rb:392:in `_run__1988912717346764301__call__callbacks'
  activesupport (4.0.0.rc1) lib/active_support/callbacks.rb:80:in `run_callbacks'
  actionpack (4.0.0.rc1) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
  actionpack (4.0.0.rc1) lib/action_dispatch/middleware/reloader.rb:64:in `call'
  actionpack (4.0.0.rc1) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
  better_errors (1.1.0) lib/better_errors/middleware.rb:84:in `protected_app_call'
  better_errors (1.1.0) lib/better_errors/middleware.rb:79:in `better_errors_call'
  better_errors (1.1.0) lib/better_errors/middleware.rb:56:in `call'
  actionpack (4.0.0.rc1) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
  actionpack (4.0.0.rc1) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.0.0.rc1) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.0.0.rc1) lib/rails/rack/logger.rb:21:in `block in call'
  activesupport (4.0.0.rc1) lib/active_support/tagged_logging.rb:67:in `block in tagged'
  activesupport (4.0.0.rc1) lib/active_support/tagged_logging.rb:25:in `tagged'
  activesupport (4.0.0.rc1) lib/active_support/tagged_logging.rb:67:in `tagged'
  railties (4.0.0.rc1) lib/rails/rack/logger.rb:21:in `call'
  actionpack (4.0.0.rc1) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
  rack (1.5.2) lib/rack/runtime.rb:17:in `call'
  activesupport (4.0.0.rc1) lib/active_support/cache/strategy/local_cache.rb:83:in `call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  actionpack (4.0.0.rc1) lib/action_dispatch/middleware/static.rb:64:in `call'
  railties (4.0.0.rc1) lib/rails/engine.rb:511:in `call'
  railties (4.0.0.rc1) lib/rails/application.rb:96:in `call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  rack (1.5.2) lib/rack/content_length.rb:14:in `call'
  rack (1.5.2) lib/rack/handler/webrick.rb:60:in `service'
  /Users/lexi87/.rvm/rubies/ruby-2.0.0-p353/lib/ruby/2.0.0/webrick/httpserver.rb:138:in `service'
  /Users/lexi87/.rvm/rubies/ruby-2.0.0-p353/lib/ruby/2.0.0/webrick/httpserver.rb:94:in `run'
  /Users/lexi87/.rvm/rubies/ruby-2.0.0-p353/lib/ruby/2.0.0/webrick/server.rb:295:in `block in start_thread'

路线:

                  Prefix Verb     URI Pattern                                   Controller#Action
             sidekiq_web          /sidekiq                                      Sidekiq::Web
                  signup GET      /signup(.:format)                             users#new
                   login GET      /login(.:format)                              sessions#new
                  logout GET      /logout(.:format)                             sessions#destroy
                    edit GET      /edit(.:format)                               users#edit
                         GET      /profile/:id(.:format)                        users#show
                         GET      /profile/:id/settings(.:format)               users#edit
                         GET      /settings/:id(.:format)                       users#settings

    notifications_create GET|POST /paypal/ipn(.:format)                         notifications#create
             admin_index GET      /admin(.:format)                              admin#index
                         POST     /admin(.:format)                              admin#create
               new_admin GET      /admin/new(.:format)                          admin#new
              edit_admin GET      /admin/:id/edit(.:format)                     admin#edit
                   admin GET      /admin/:id(.:format)                          admin#show
                         PATCH    /admin/:id(.:format)                          admin#update
                         PUT      /admin/:id(.:format)                          admin#update
                         DELETE   /admin/:id(.:format)                          admin#destroy

           settings_user GET      /users/:id/settings(.:format)                 users#settings
             follow_user POST     /users/:id/follow(.:format)                   users#follow
           unfollow_user POST     /users/:id/unfollow(.:format)                 users#unfollow
                         GET      /users/:id/follow(.:format)                   users#follow
       follow_popup_user GET      /users/:id/follow_popup(.:format)             users#follow_popup
            search_users POST     /users/search(.:format)                       users#search
                   users GET      /users(.:format)                              users#index
                         POST     /users(.:format)                              users#create
                new_user GET      /users/new(.:format)                          users#new
               edit_user GET      /users/:id/edit(.:format)                     users#edit
                    user GET      /users/:id(.:format)                          users#show
                         PATCH    /users/:id(.:format)                          users#update
                         PUT      /users/:id(.:format)                          users#update
                         DELETE   /users/:id(.:format)                          users#destroy              
                    root GET      /                                             users#index
                         GET      /users(.:format)                              users#index
                         POST     /users(.:format)                              users#create
                         GET      /users/new(.:format)                          users#new
                         GET      /users/:id/edit(.:format)                     users#edit
                         GET      /users/:id(.:format)                          users#show
                         PATCH    /users/:id(.:format)                          users#update
                         PUT      /users/:id(.:format)                          users#update
                         DELETE   /users/:id(.:format)                          users#destroy

用户模型:

class User < ActiveRecord::Base
  acts_as_messageable
  has_secure_password
  attr_accessible :role, :notification_id, :sender_id, :receiver_id, :conversation_id, :no_email, :average_response_time, :response_rate, :response_total, :name, :time_zone, :code, :lat, :lon, :city, :age, :age_end, :password_confirmation, :about_me, :feet, :inches, :password, :birthday, :career, :children, :education, :email, :ethnicity, :gender, :height, :name, :password_digest, :politics, :religion, :sexuality, :user_drink, :user_smoke, :username, :zip_code, :user_sex
  attr_accessor :user_sex
  # this prevented user from registering as I don't have timezone select on user reg form
  # validates_inclusion_of :time_zone, in: ActiveSupport::TimeZone.zones_map(&:name)
  has_one :subscription
  has_many :photos
  has_many :letsgos, dependent: :destroy
  belongs_to :default_photo, :class_name => "Photo"  
  has_many :notifications
  has_many :questions, foreign_key: :recipient_id
  has_many :sent_questions, class_name: 'Question', foreign_key: :sender_id

  belongs_to :location
  belongs_to :zip
  belongs_to :avatar, class_name: 'Photo'
  has_many :received_messages, class_name: 'Message', foreign_key: 'recipient_id'
  has_many :sent_messages, class_name: 'Message', foreign_key: 'sender_id'
  has_many :users, dependent: :destroy
  has_many :relationships, foreign_key: "follower_id", dependent: :destroy
  has_many :followed_users, through: :relationships, source: :followed
  has_many :reverse_relationships, foreign_key: "followed_id", class_name: "Relationship", dependent: :destroy
  has_many :followers, through: :reverse_relationships, source: :follower
  validates_format_of :zip_code,
                  with: /\A\d{5}-\d{4}|\A\d{5}\z/,
                  message: "should be 12345 or 12345-1234"
  validates_uniqueness_of :email
  validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
  validates_uniqueness_of :username
  validates_presence_of :username
  validates_format_of :username, :with => /\A[a-zA-Z0-9]+\Z/, :message => "should only contain letters or numbers"
  validates :password, :presence => true,
                       :confirmation => true,
                       :length => {:within => 6..40},
                       :on => :create
  before_create { generate_token(:auth_token) }
  ROLES = %w[admin user guest banned]
  scope :except_user, ->(user) { where('users.id != ?', user.id)}
  # models/user.rb
  after_create :setup_gallery

  def to_param
     username
   end

   def subscribed?
      subscription.present?
    end

    def paid?
      subscriptions.where(cancelled: nil).exists?
    end

    def reg?
      !subscription.cancelled? if subscription
    end

    def mailboxer_email(object)
        if self.no_email
          email
        else
            nil
        end
    end
  def location

      if Location.by_zip_code(self.zip_code.to_s).any?
          # you can return all here if you want more than one
          # for testing just returning the first one
          return Location.by_zip_code(self.zip_code.to_s).first
      else
          return nil
      end
  end

  def address
    "#{location.city}, #{location.state}" rescue nil
  end

   def over_18
      if birthday + 18.years > Date.today
        errors.add(:birthday, "can't be under 18")
      end
    end

    def age
      now = Time.now.utc.to_date
      now.year - birthday.year - ((now.month > birthday.month || (now.month == birthday.month && now.day >= birthday.day)) ? 0 : 1)
    end

  def to_s; username
  end

  def has_role?(role_name)
    role.present? && role.to_sym == role_name.to_sym
  end

  def send_password_reset
    generate_token(:password_reset_token)
    self.password_reset_sent_at = Time.zone.now
    save!
    UserMailer.password_reset(self).deliver
  end

  def generate_token(column)
    begin
      self[column] = SecureRandom.urlsafe_base64
    end while User.exists?(column => self[column])
  end

  def self.with_age_range(year_range)
    today = Date.today
    where birthday: (today - year_range.max.years)..(today - year_range.min.years)
  end

  def name
    return "#{first_name} #{last_name}"
   end

  private
  def setup_gallery
     Gallery.create(user: self)
   end
end

路线:

  get 'signup' => 'users#new'
  get 'login' => 'sessions#new'
  get 'logout' => 'sessions#destroy'
  get 'edit' => 'users#edit'
  get "/profile/:id" => "users#show"
  get "profile/:id/settings" => 'users#edit'
  get 'settings/:id' => 'users#settings'
  get "subscriptions/cancelsubscription"
  get "subscriptions/updatesubscription"
  get "subscriptions/changecard"
  get "subscriptions/suspend"
  get "subscriptions/updatebilling"
  get "subscriptions/reactivate"
  get ":id/updatebilling" => "users#update_stripe_billing"
  match '/edit_card',   to: 'subscriptions#edit_card',   via: 'get'
  match '/update_card', to: 'subscriptions#update_card', via: 'post'
  get '/relationships/set_follow' => 'relationships#set_follow'



    resources :messages do
      member do
      post :askout
      end
    end


  match '/paypal/ipn' => 'notifications#create', :via => [:get, :post], :as => 'notifications_create'

  resources :admin
  resources :charges
  resources :subscriptions
  resources :plans
  get 'paypal/checkout', to: 'subscriptions#paypal_checkout'

  resources :sessions
  resources :contacts, only: [:new, :create]
  resources :password_resets
  resources :galleries
  resources :photos do
    member do
      post :avatar
    end
  end
  resources :searches
  resources :sessions,      only: [:new, :create, :destroy]
  resources :relationships, only: [:create, :destroy]
  resources :letsgos, only: [:create, :destroy]
  resources :users do  
    get 'settings', on: :member  
    post 'follow', on: :member 
    post 'unfollow', on: :member
    get "follow", on: :member 
    get 'follow_popup', on: :member
    post :search, on: :collection
  end

  root to: 'users#index'

  resources :users do
  end

 resources :conversations do
   member do
     post :reply
     post :trash
     post :untrash
   end
 end

  resources :payments, only: [:show, :create, :destroy] do
     collection do
       get :success
       get :cancel
       post :notify
     end     
   end

2 个答案:

答案 0 :(得分:1)

我同意riecaro2。你有一个关系has_many:users,dependent :: destroy在表用户没有user_id字段。这就是MySql所说的。

答案 1 :(得分:0)

使用

User.find_by(username: params[:id]).destroy

代替,

User.find(username: params[:id]).destroy

User.find(params[:id]).destroy 

因为您在参数列表

中将id作为username传递