0

我在我的显示操作中的帖子控制器中收到错误消息“错误数量的参数错误(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
4

2 回答 2

6

You'll want to read the the latest Rails Active Record Query Interface Guide. A lot has changed lately. The short answer is that you now chain together conditions. And .all does not take any arguments -- as the error message is telling you. Instead, you want to use the .order() method:

@posts = Post.order(created_at: :desc)
于 2014-08-19T20:00:28.250 回答
2

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

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

或所有帖子

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

考虑到这样一个事实,你在show行动中写这个,你可能是首先考虑的。


还有关于强参数的小建议。而不是写这个@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
于 2014-08-19T19:58:34.987 回答