Nissim P.
Nissim P.

Reputation: 31

Rails: Card.id has no value

I'm a newbie in RoR, trying to do the "Pragmatic Agile Web Development" depot application. The application needs to keep track of all the items added to the cart by the buyer.

Here is the creation of the Cart model:

rails generate scaffold cart

And this is the application controller code:

class ApplicationController < ActionController::Base

protect_from_forgery

private
  def current_cart
    Cart.find(session[:cart_id])
  rescue ActiveRecord::RecordNotFound
    cart = Cart.create
    session[:cart_id] = cart.id
    cart
  end
end

My questions:

  1. In the "scaffold" command I didn't specify any column name for this table, but still the Cart seems to have one column called "id". Is the scaffold command auto generate an "id" column?
  2. In this rescue block, a new Cart object is created without setting any value to "Card.id". on the next line we assign this "id" value to "session[:cart_id] = cart.id". what is the value that will be stored?

Your answers will be appreciated,

Thanks

Upvotes: 2

Views: 74

Answers (1)

Samiron
Samiron

Reputation: 5317

Answer of 1: Yes id is the autoincremented id column generated automatically by the scaffold generator. Each time a new entry will be created a new id will be generated.

Answer of 2: Yes a new object of Cart is created unless it can find one by the already stored cart_id in session. Hence after creating a new Cart, it saves the new cart_id in session for future uses. Like on next request when the controller will again call current_cart function, it will get a valid cart_id from session and the corresponding Cart object as well.

If you are not really aware of session or how sessions are handled in ROR, then you can follow these links.

Let me know anything left confusing.

Upvotes: 2

Related Questions