我目前收到错误:
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
我的索引页面的模板如下:
<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#*
相关的其他模板上遇到类似的错误。
答案 0 :(得分:1)
您有posts
作为users
的嵌套资源。您需要有new_user_post_path(@user)
之类的路径。
确保你有一个
@user
传递这个助手。
index
posts
@user = User.first
行动中的{{1}}动作取得这样的用户。
{{1}}
答案 1 :(得分:0)
您需要在User
的路径中传递Post
个对象
像这样的东西
@user or current_user
new_user_post_path(@user)