为什么我的 PostsController 出现 undefined method 'action' 错误?(数据表不存在)

6
我是一个编程新手,所以我决定开始学习Ruby on Rails 4.0.0版本的指南。然而,我遇到了问题接踵而至。我目前正在运行4.0.0版本,并且按照指南的步骤进行操作。
当我到达5.2第一个表单时,我开始遇到错误,并在其他人的帖子中寻求解决方法。但这个错误似乎没有发生在其他人身上,所以我在这里描述一下:
NoMethodError in PostsController#index
undefined method `action' for PostsController(Table doesn't exist):Class

这是我的代码:

class PostsController < ActiveRecord::Base                             

attr_accessible :title, :text                            

  def new                                                              
  end                                                                  

  def create                                                           
    @post = Post.new(params[:post].permit(:title, :text))              

    @post.save                                                         
    redirect_to @post                                                  
  end                                                                  

  def show                                                             
    @post = Post.find(params[:id])                                     
  end                                                                  

  def index                                                            
    @post = Post.all                                                   
  end                                                                  

  def action                                                           
  end                                                                  

  private                                                              
    def post_params                                                    
      params.require(:post).permit(:title, :text)                      
    end                                                                

end   

这是我的观点:
<p>
  <strong> Title: </strong>
  <%= @post.title %>
</p>

<p>
  <strong> Text: </strong>
  <%= @post.text %>
</p>

我的表单是:

<h1> New Post </h1>

 <%= form_for :posts, url: posts_path do |f| %>

  <p>
   <%= f.label :title %><br>
   <%= f.text_field :title %>
  </p>

  <p>
    <%= f.label :text%><br>
    <%= f.text_area :text %>
  </p>

  <p>
   <%= f.submit %>
  </p>
  <% end %>

错误提示我没有定义动作方法,但我不确定如何首先定义一个,然而这还不是全部。当我访问我的本地主机:3000/posts/new页面时,我得到同样的错误,但是针对PostsController#new
有人能帮帮我吗!

3
“Table doesn't exist”应该是一个很好的线索。那张表在你的数据库中存在吗? - the Tin Man
我查了一下数据库,似乎里面没有表格,你有什么建议可以告诉我如何添加一个表格或者需要做些什么来创建一个吗? - Therafer
1个回答

21

不清楚您的控制器为什么要继承自模型类:

class PostsController < ApplicationController
  # ...
end

我之所以要继承一个模型类,是因为如果没有继承ActiveRecord::Base,attr_accessible就无法正常工作。如果没有attr_accessible,似乎在表单中调用标题和文本会出现问题。 - Therafer
其实我刚刚意识到我必须将attr_accessible放在实际的Active Record Base中,并将控制器改回ApplicationController!谢谢你的帮助。 - Therafer
ActiveRecord 只适用于模型。像您所做的那样在模型中放置该声明是正确的方法。 - tadman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接