undefined方法`micropost_path'ROR教程第3版

时间:2016-01-26 00:15:39

标签: ruby-on-rails ruby-on-rails-4 controller

为什么我在StaticPagesController中得到以下“未定义的方法`micropost_path'”,错误,即使我逐字复制了Hartl的代码?

以下是一些代码。

的routes.rb

Rails.application.routes.draw do
root                'static_pages#home'
get    'help'    => 'static_pages#help'
get    'about'   => 'static_pages#about'
get    'contact' => 'static_pages#contact'
get    'signup'  => 'users#new'
get    'login'   => 'sessions#new'
post   'login'   => 'sessions#create'
delete 'logout'  => 'sessions#destroy'
resources :users
resources :account_activations, only: [:edit]
resources :password_resets,     only: [:new, :create, :edit, :update]
resources :microposts,          only: [:create, :edit]
end   

StaticPages控制器

class StaticPagesController < ApplicationController
def home
if logged_in?
  @micropost  = current_user.microposts.build
  @feed_items = current_user.feed.paginate(page: params[:page])
end
end

def help
end

def about
end

def contact
end

end

MicropostsController

class MicropostsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
before_action :correct_user,   only: :destroy


def create
@micropost = current_user.microposts.build(micropost_params)
if @micropost.save
  flash[:success] = "Micropost created!"
  redirect_to root_url
else
  @feed_items = []
  render 'static_pages/home'
end
end

def destroy
 @micropost.destroy
 flash[:success] = "Micropost deleted"
 redirect_to request.referrer || root_url
end


private

def micropost_params
 params.require(:micropost).permit(:content)
end

def correct_user 
@micropost = current_user.microposts.find_by(id: params[:id])
redirect_to root_url if @micropost.nil?
end

end

本网站上针对此问题的两个答案因其他原因得以解决。

例如写作

micropost 

而不是

microposts

如果我没有弄错的话,我在这里没有这些语法错误。知道其他问题可能导致这个吗?

P.S。在学习本教程的同时使用cloud9 IDE。

1 个答案:

答案 0 :(得分:0)

在routes.rb中,我有以下微博资源

resources :microposts,          only: [:create, :edit]

相反,它应该是

resources :microposts,          only: [:create, :destroy]

:destroy

失踪了。

在运行'rake routes'后发现了这个......

得到了这条路线

edit_micropost GET    /microposts/:id/edit(.:format) microposts#edit

而不是

micropost DELETE /microposts/:id(.:format) microposts#destroy

这显示了应该在控制器中的相应操作的路由。