Welcome/home page in Ruby on Rails - best practice

后端 未结 7 1489
温柔的废话
温柔的废话 2020-12-07 09:05

My homepage (or welcome page) will consist of data from two models (lets call them authors and posts). I am new to rails and not sure what is the best way to accomplish this

7条回答
  •  攒了一身酷
    2020-12-07 09:32

    The question is, is your home page just a landing page or will it be a group of pages? If it's just a landing page, you don't expect your users to hang around there for long except to go elsewhere. If it's a group of pages, or similar to an existing group, you can add an action to the controller it's most like.

    What I've done for my current project is make a controller named Static, because I need 3 static pages. The home page is one of these, because there isn't anything to see or do except go elsewhere.

    To map a default route, use the following in routes.rb:

    # Place at the end of the routing!
    map.root :controller => 'MyController', :action => :index
    

    In my case this would be:

    map.root :controller => 'static', :action => :index
    

    If you wish to, you could create a controller just for this home page. I'd call it main, or something that you can remember which relates to the home page. From there you can get your data and your models and defer to the output view.

    class MainController < ApplicationController
      def index
        @posts = Posts.find(:all, :limit => 10, :order => 'date_posted', :include => :user)
      end
    end
    

    Assuming you have your model relationships defined correctly, the template to match it will be very simple.

    Good luck, hope this helps.

提交回复
热议问题