2013-08-29 45 views
1

我一直在研究Ruby on Rails v.4.0.0指南,並剛剛完成了最後一段代碼。但我有3個問題,我認爲可能來自1個來源。我的SHOW方法似乎不管用什麼原因。我有一個「顯示」視圖,但它給了我錯誤「無法找到帖子id = show」。並告訴我我的PostsController的第35行是錯誤的。我看了一會兒,似乎無法找到任何具有類似足夠的東西的人。所以這裏是控制器和視圖。找不到帖子id = show?

控制器:

1 class PostsController < ApplicationController 
    2 
    3 http_basic_authenticate_with name: "dhh", password: "secret", 
    4 except: [:index, :show] 
    5 
    6 def new 
    7  @post = Post.new 
    8 end 
    9 
    10 def create 
    11  @post = Post.new(params[:post]) 
    12 
    13  if @post.save 
    14  redirect_to @post 
    15  else 
    16  render 'new' 
    17  end 
    18 end 
    19                  
    20 def edit 
    21  @post = Post.find(params[:id]) 
    22 end 
    23 
    24 def update 
    25  @post = Post.find(params[:id]) 
    26 
    27  if @post.update(params[:post].permit(:title, :text)) 
    28  redirect_to @post 
    29  else 
    30  render 'edit' 
    31  end 
    32 end 
    33 
    34 def show 
    35  @post = Post.find(params[:id]) 
    36 end 
    37 
    38 def index 
    39  @post = Post.all 
    40 end 
    41 
    42 def destroy 
    43  @post = Post.find(params[:id]) 
    44  @post.destroy 
    45 
    46  redirect_to posts_path 
    47 end 
    48 
    49 private 
    50  def post_params 
    51  params.require(:post).permit(:title, :text) 
    52  end 
    53 end 

查看:

1 <%= @post.each do |post| %> 
    2 <p> 
    3 <strong> Title: </strong> 
    4 <%= @post.title %> 
    5 </p> 
    6 
    7 <p> 
    8 <strong> Text: </strong> 
    9 <%= @post.text %> 
    10 </p> 
    11 
    12 <%end%> 
    13 
    14 <h2> Comments </h2> 
    15 <%= render @post.comments %> 
    16 
    17 <h2>Add a comment:</h2> 
    18 <%= render "comments/form" %> 
    19 
    20 <%= link_to 'Back to Posts', posts_path %> 
    21 | <%= link_to 'Edit Post', edit_post_path(@post) %> 

完整的錯誤是:

的ActiveRecord :: RecordNotFound在PostsController#顯示 可能找不到ID後=顯示

注:我是誦讀困難的,所以它可能只是一個拼寫ling error ...

+0

你能告訴我們你的'routes.rb'? –

回答

5

params[:id]等於"show"而不是一些真實的ID。可能你試圖訪問錯誤的網址,如/posts/show而不是/posts/1或任何ID。

+0

嗯......這似乎確實是問題,但在同一時間指導說我應該能夠看到我的帖子/顯示在我的網址和我的帖子/索引給我同樣的錯誤(因此多個問題=> 1源),所以我應該給你更多的文件,或者只是我的一部分愚蠢的錯誤? – Therafer

+0

@Therafer你在看[這個指南](http://guides.rubyonrails.org/getting_started.html)嗎?當他們談論'.erb'模板時,你可能會感到困惑。您的視圖文件的名稱確實是'/ posts/show',後面加上了'.html.erb',但這對URL沒有任何影響(不是直接反正)。最終,您的路由文件(routes.rb)指示哪個控制器操作響應請求的URL,並呈現一個類似命名的視圖模板(除非您在控制器中另行指定) –

+0

如何更改以響應/ posts/show ?id = 1而不是/ posts/1 ??我在我的應用程序中遇到同樣的問題,但我可能需要指定更多的參數,而不僅僅是一個ID – Riptyde4

2

我無法評論,所以這是一個現在的答案,但您能否確認您要使用的URL包含您要查找的帖子的ID?如果它正在尋找ID爲'show'的帖子,聽起來像你可能要yourUrl/posts/show而不是yourUrl/posts/1

0

您是否將PostController放置在routes.rb中?

資源:後

+0

該請求正確路由到PostsController中的:show方法。如果這個請求不在路由文件中,請求不會那麼快。 –