I have such a problem, I just started to learn RoR.

I have data in the database (Blog Name, Title, Content). I need to select the last 5 entries, how to implement it? What to write and where? In the controller? What exactly to write?

This is the homepage view, the second link should go to the page with the selected five entries.

<div id="head"><h2 align="center">Музыкальный блог musicasfreedom</h2> <p id="come"> <%= link_to "Войти", posts_path %> <br> <%= link_to "Показать пять последних",posts_path(@index1)%> def index1 @index1 = Post.limit(5) respond_to do |format| format.html # index.html.erb format.json { render json: @posts } end end def index @posts = Post.all respond_to do |format| format.html # index.html.erb format.json { render json: @posts } end end 

Now I have ALL entries on both links ...

    2 answers 2

    You need to refer to different controller methods. To do this, write your index1 in routes.rb.

    rake routes

    and you will see a list of all available methods.

    In general, read something like this tutorial, I think now you just do not understand the principles of the work of RoR.

    • And what exactly should I write in routes.rb Blog: Application.routes.draw do resources: olas resources: posts do resources: comments end get "home / index" root: to => "home # index" - alexkate
    • you need to register there a route (route) which will be connected with a method of some controller. I say, read the textbooks first, otherwise write a bunch of bad code, a piece of which you have already provided. - AlexDenisov
    • Thanks, it turned out! Thanks for prompting with routing! - alexkate

    This question has already been - tyts

    In short, you need to write to get the last 5 records.


    This will return the last 5 posts, and the newest one will be the first, this code must be understandable in some controller action (each public controller method is action). And then in the view output the data in the records.

    I was still embarrassed in your code that logging into your blog you give a link to blogs -

     <%= link_to "Войти", posts_path %> 

    This is pretty weird.

    • The problem for those who forgive is not in the last five, but in the tracks as a whole :) - AlexDenisov