简体   繁体   中英

Ruby on Rails layouts and rendering

I'm new to RoR and I'm a little bit confused with Rails MWC. I feel like I misunderstand something.

For example, I want to have home page where I could render top 5 articles and top 5 products. Products and articles have no relations at all, it is totally separate data.

So what I try to do is, i crate 2 sacffolds products and articles, and 1 controller for home page. I root to homepage controller. Then in homepage template i try to render products and article template. I get an error that methods which are used in products and articles controllers are undefined.

I don't understand where is problem. Is this kind of template rendering one template inside another is not Rails convention. Or I have bugs in my code.

First, you need to instantiate your variables @products and @articles (this is an example) on your controller method. Then you can render the view.

Pay attention to add an @ before. Only variables with an @ will be available on your rendering view.

By default, when you call a GET for /products you'll arrive on the index method. At the end of this method, if not any view is specified, Rails will render views/products/index . In this view, you'll access all variables instantiate with an @ and do whatever you want with.

I don't see your code but in this case I'm quite sure you have bugs in it.

app/controllers/home_controller.rb

class HomeController < ApplicationController

  def index
    @products = Product.top5 # Your logic to fetch top 5
    @articles = Article.top5
  end

end

app/views/home/index.html.erb

<% @products.each do |product| %>
  <%= product.name %>
<% end %>
<% @articles.each do |article| %>
  <%= article.name %>
<% end %>

This is perfectly fine, I've done that multiple times. Consider that in Rails you don't have any relation between controller and models, there are convention but Rails controller is not bound at all to any model

First, yes, a template rendering another controller's template (not a partial) is not within Rails conventions. A scaffold is a "single-resource" controller: it takes your model definition and generates a basic controller for editing and displaying that particular model (ie, Product ). What you really need to do is use the two models you've generated in the home page controller, kinda like this:

class HomePageController < ApplicationController
  def index
    @articles = Article.top_5
    @products = Product.top_5
    # Render the @articles and @products in the view.
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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