我是编程和 Rails 的新手。请善待。我正在关注有关如何构建您的第一个博客的入门 Rails 指南 http://guides.rubyonrails.org/getting_started.html
我已经到了第 6 部分,我打算将评论模型添加到帖子模型中。按照说明操作后,我收到此错误。
SyntaxError in PostsController#index
/home/nadia/blog/app/models/post.rb:5: syntax error, unexpected ..., expecting ']' [...]
Extracted source (around line #4):
def index
@post = Post.all
end
这是我的 路线.rb
1 Blog::Application.routes.draw do
2
3
5
6
7 resources :posts
8
9 # You can have the root of your site routed with "root"
10 root 'welcome#index'
11
12
13 resources :posts do
14 resources :comments
15 end
这是我的 post_controller.rb
1 class PostsController < ApplicationController
2
3 def index
4 @post = Post.all
5 end
6
7 def new
8 @post = Post.new
9 end
10 def create
11 @ post = Post.new(params[:post].permit(:title, :text))
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 destroy
35 @post = Post.find(params[:id])
36 @post.destroy
37
38 redirect_to posts_path
39 end
40
41 def show
42 @post = Post.find(params[:id])
43 end
44
45 private
46 def post_params
47 params.require(:post).permit(:title, :text)
48 end
49 end
评论 Controller .rb
1 class CommentsController < ApplicationController
2 def create
3 @post = Post.find(params[:post_id])
4 @comment = @post.comments.create(params[:comment].permit(:commenter, :body))
5 redirect_to post_path(@post)
6 end
7 end
和我的 index.html.erb
1 <h1>Listing posts</h1>
2 <%= link_to 'New post', new_post_path %>
3 <table>
4 <tr>
5 <th>Title</th>
6 <th>Text</th>
7 <th></th>
8 </tr>
9
10
11 <% @post.each do |post| %>
12 <tr>
13 <td><%= post.title %></td>
14 <td><%= post.text %></td>
15 <td><%= link_to 'Show', post %></td>
16 <td><%= link_to 'Edit', edit_post_path(post) %></td>
17 <td><%= link_to 'Destroy', post_path(post), method: :delete, data : { confirm: 'Are you sure?'} %> </td>
18 </tr>
19 <% end %>
20 </table>
请帮忙,如果我可以提供更多信息来帮助你,请告诉我。
最佳答案
在 Controller 的 index 方法中,您在应该使用 @posts 的时候使用了 @post。你在 index.html.erb 的第 11 行有同样的错误。 @posts 是一个集合。 @post 指的是单个帖子。
关于ruby-on-rails - 为什么当我尝试按照 ruby on rails 入门指南添加第二个模型时,rails 在 PostsController#index 中给我一个 SyntaxError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21667205/