2013-03-05 27 views
2

我目前得到的錯誤:無法找到new_post_path,和其他模板函數

undefined local variable or method `new_post_path' 

我的索引頁上的模型設置:

post.rb:

class Post < ActiveRecord::Base 
    attr_accessible :postcontent, :poster, :postname 
    belongs_to :user 
end 

user.rb:

class User < ActiveRecord::Base 
    attr_accessible :email, :password, :username 
    has_many :posts 
end 

My templ吃了我的索引頁面如下:

<h1>Listing posts</h1> 

<table> 
    <tr> 
    <th>Postname</th> 
    <th>Postcontent</th> 
    <th>Poster</th> 
    <th></th> 
    <th></th> 
    <th></th> 
    </tr> 

<% @posts.each do |post| %> 
    <tr> 
    <td><%= post.postname %></td> 
    <td><%= post.postcontent %></td> 
    <td><%= post.poster %></td> 
    <td><%= link_to 'Show', post %></td> 
    <td><%= link_to 'Edit', edit_post_path(post) %></td> 
    <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td> 
    </tr> 
<% end %> 
</table> 

<br /> 

<%= link_to 'New Post', new_post_path %> 

,併爲這個控制器是:

def index 
    @posts = Post.all 

    respond_to do |format| 
     format.html # index.html.erb 
     format.json { render json: @posts } 
    end 
    end 

用於路由,我rake routes輸出爲:

user_posts GET /users/:user_id/posts(.:format)   posts#index 
       POST /users/:user_id/posts(.:format)   posts#create 
new_user_post GET /users/:user_id/posts/new(.:format)  posts#new 
edit_user_post GET /users/:user_id/posts/:id/edit(.:format) posts#edit 
    user_post GET /users/:user_id/posts/:id(.:format)  posts#show 
       PUT /users/:user_id/posts/:id(.:format)  posts#update 
       DELETE /users/:user_id/posts/:id(.:format)  posts#destroy 
     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 
       PUT /users/:id(.:format)      users#update 
       DELETE /users/:id(.:format)      users#destroy 
      root  /          home#index 

和我的路由文件是:

resources :users do 
    resources :posts 
    end 
    root :to => "home#index" 

但值得注意的是,我在全部posts#*有關的其他模板上得到類似的錯誤。

回答

1

你有postsusers嵌套的資源。你需要有一個像new_user_post_path(@user)這樣的路徑。 確保你有一個 @user傳遞此幫手。

在你index行動的posts控制器取得這樣的用戶。

@user = User.first 
0

你需要傳遞User對象Post的路徑 類似的東西

@user or current_user 
new_user_post_path(@user) 
+0

我是一個初學者,當談到RoR,你能給我一個例子嗎? – 2013-03-05 05:58:21

+0

由於可以使用用戶創建帖子,因此每次我們需要將用戶的對象傳遞給帖子控制器,或者如果您正在使用設計,那麼您可以獲取current_user對象。 – 2013-03-05 06:12:12