CHID
CHID

Reputation: 1643

what does the following code do?

i created a project

demo
in rails. i then created a scaffolded application by giving
 rail_apps/demo> script server products title :stiring,description :text,url: string 

Then i gave

 http://localhost:3000/products/ 

The products_controller.rb contains the following piece of code

class ProductsController < ApplicationController
  # GET /products
  # GET /products.xml
  def index
    @products = Product.find(:all)

respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @products }
end
  end
end

but i really cannot understand those four lines of code. can anyone give me a lead?

Upvotes: 0

Views: 322

Answers (2)

Theo
Theo

Reputation: 132862

To render the index action first find all products and assign them to the variable @products, then respond with either HTML or XML, depending on what the client wants (for example if the URL ends in .xml the client wants XML.

Render index.html.erb if the client wants HTML (Rails finds the template itself based on the controller name and action name, so ProductsController and index makes Rails look for app/views/products/index.html.erb.

Render XML from the @products variable if the client wants XML (Rails can automatically serialize an ActiveRecord object, or array of objects, as XML by looking at its properties).

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

@products = Product.find(:all)

fetches all products from database.

respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @products }
end

is a common pattern in RoR. Based on the request the controller renders a different view. For example if you request /products it will pass the products to the index.html.erb view which is just an html template. If the request is /products.xml it will serialize the products to a XML file and send this file as response.

Upvotes: 5

Related Questions