【问题标题】:Wrong number of arguments error(1 for 0) in Posts controller, rails 4?Posts 控制器,rails 4 中的参数数量错误(1 表示 0)?
【发布时间】:2014-10-13 01:21:37
【问题描述】:

我在显示操作中的帖子控制器中收到错误消息“参数数量错误错误(1 代表 0)。我将评论该特定行的结尾。感谢您的帮助。

def show
  @post = Post.all(:order => 'created_at DESC') #this is the error line
end

def new
  @post = Post.new
end

def create
  @post = Post.new(params[:post])

  if @post.save
    redirect_to @post
  else
   render :new
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 ruby-2.1


    【解决方案1】:

    您要么必须显示 1 个帖子,要么是:

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

    或所有帖子

    @posts = Post.order('created_at DESC') # index
    

    考虑到这一事实,您在show 操作中写了这个,您可能是指第一个。


    还有关于strong parameters 的小建议。 与其写这个@post = Post.new(params[:post]),不如写#create

    @post = Post.new(post_params) 
    
    private
    
    def post_params
      params.require(:post).permit(:title, :body) #whatsoever your post has
    end
    

    【讨论】:

    • 好的,我进行了更改以显示 1 个帖子。现在它只是在创建新帖子时路由到创建视图。我的节目视图应该是什么样子?
    • 你要创建什么路线?
    • 我只是使用了资源路由。 => 资源:帖子
    • 创建 show.html.erb 并粘贴 <h1>Posts</h1> <% @posts.each do |post| %> Title: <%= post.title %><br> <% end %> 这样您就可以添加任何帖子的字段..
    • 好的,谢谢,我仍然不明白为什么在发布新帖子后它会转到创建视图而不是显示视图..
    【解决方案2】:

    您会想阅读最新的Rails Active Record Query Interface Guide。最近发生了很多变化。简短的回答是您现在将条件链接在一起。 .all 不接受任何参数——正如错误消息告诉你的那样。相反,您想使用.order() 方法:

    @posts = Post.order(created_at: :desc)
    

    【讨论】:

    • 我不知道为什么会有反对票。 .all 在 4.1 版本中不再接受任何参数是正确的。在之前的 4.0 版本中,相信你仍然可以使用.all 中的旧选项参数,但不能再使用了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    相关资源
    最近更新 更多