我在嘗試在Hartl的Ruby on Rails教程中實現示例應用程序時遇到了一個奇怪的問題。RoR教程Michael Hartl刪除Microposts也刪除用戶
當我刪除微柱,將發生以下情況:
- 的微柱被刪除。
- 該用戶也被刪除。
- 指示註冊頁面。
只有第一步應該發生。用戶不應該被刪除。當我刪除微博時,控制檯跟蹤顯示以下內容:
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
您可以在上面看到如何執行destroy操作(如教程中指定的那樣)。所以我不確定問題是什麼。
這裏是應用程序/模型/ 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
欣賞任何幫助。
你的'app/models/micropost.rb'看起來像什麼? –
謝謝你看這馬立克。我在上面添加了micropost.rb的代碼。在教程中解釋了dependent::destroy,以便在用戶被刪除時刪除屬於該用戶的所有微博。 –
@AbeChallah,如果你想刪除屬於用戶的所有微博,那麼你應該在'User.rb'中加入'dependent::destroy',就像'has_many:microposts,dependent :: destroy' – vee