简体   繁体   English

Controller 语法 Ruby on Rails 6

[英]Controller syntax Ruby on Rails 6

Having an issue with displaying only three posts on a page.在页面上仅显示三个帖子时遇到问题。 Here is the closest I've gotten to getting the controller working with a param.这是我最接近让 controller 与参数一起工作的方法。

def index

    @Post = Post.all

    @Posts = Post.find.limit('3').order('date_posted')

  end

This is rendering a syntax error of sorts because it wants an ID, but I don't want to give it an ID, I want it to find the three most recent posts.这会呈现某种语法错误,因为它需要一个 ID,但我不想给它一个 ID,我希望它找到最近的三个帖子。 How should I go about that?我应该如何 go 关于那个?

Try this way试试这个方法

def index
  @recent_posts = Post.limit(3).order(date_posted: :desc)
end

What's wrong in your code你的代码有什么问题

  • all gives you all the objects for a model all为您提供 model 的所有对象
  • find and find_by give you just one object which meet the id passed to find or the first one which meets the conditions passed to find_by findfind_by给你一个 object 满足传递给find的 id 或第一个满足传递给find_by的条件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM