我在尝试实现 Hartl 的 Ruby on Rails 教程中的示例应用程序时遇到了一个奇怪的问题。
当我删除微博时,会发生以下情况:
- 微博被删除。
- 用户也被删除。
- 被定向到注册页面。
只有第一步应该发生。用户不应该被删除。当我删除微博时,控制台跟踪显示以下内容:
Started DELETE "/microposts/1" for 127.0.0.1 at 2013-07-23 11:35:31 -0400
Processing by MicropostsController#destroy as HTML
Parameters: {"authenticity_token"=>"clfdQ1F/1ewiDnuae9OpVXSZ3S/wtieCrVYNM+Y1838=", "id"=>"1"}
User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'cUs3NX6FrzU-XnkCbGE4wg' LIMIT 1
Micropost Load (1.0ms) SELECT "microposts".* FROM "microposts" WHERE "microposts"."user_id" = 1 AND "microposts"."id" = 1 ORDER BY microposts.created_at DESC LIMIT 1
(0.0ms) begin transaction
SQL (2.0ms) DELETE FROM "microposts" WHERE "microposts"."id" = ? [["id", 1]]
User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
SQL (1.0ms) DELETE FROM "users" WHERE "users"."id" = ? [["id", 1]]
(12.0ms) commit transaction
Redirected to http://localhost:3000/
Completed 302 Found in 27ms (ActiveRecord: 16.0ms)
我不确定为什么要发送 DELETE FROM "users"。
我的 application.js 文件如下所示:
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require_tree .
我的 routes.rb 看起来像这样:
SampleApp::Application.routes.draw do
resources :users
resources :sessions, only: [:new, :create, :destroy]
resources :microposts, only: [:create, :destroy]
root :to => 'static_pages#home'
match '/signup', to: 'users#new'
match '/signin', to: 'sessions#new'
match '/signout', to: 'sessions#destroy', via: :delete
match '/help', to: 'static_pages#help'
match '/about', to: 'static_pages#about'
match '/contact', to: 'static_pages#contact'
end
microposts_controller.rb 看起来像这样:
class MicropostsController < ApplicationController
before_filter :signed_in_user, only: [:create, :destroy]
before_filter :correct_user, only: :destroy
def create
@micropost = current_user.microposts.build(params[:micropost])
if @micropost.save
flash[:success] = "Micropost created!"
redirect_to root_path
else
@feed_items = []
render 'static_pages/home'
end
end
def destroy
@micropost.destroy
redirect_back_or root_path
end
private
def correct_user
@micropost = current_user.microposts.find_by_id(params[:id])
redirect_to root_path if @micropost.nil?
end
end
您可以在上面看到销毁操作是如何实现的(如教程中所述)。所以我不确定问题是什么。
这是 app/models/micropost.rb
class Micropost < ActiveRecord::Base
# here we removed :user_id from attr_accessable for security reasons
attr_accessible :content
belongs_to :user, dependent: :destroy
validates :content, presence: true, length: { maximum: 140 }
validates :user_id, presence: true
default_scope order: 'microposts.created_at DESC'
end
感谢您对此的任何帮助。