Rails 新Rails应用程序的RVM工作流程

# create and use the new RVM gemset
$ rvm use --create 1.9.3@awesome_rails_project

# install rails into the blank gemset
$ gem install rails

# generate the new rails project
$ rails new awesome_rails_project

# go into the new project directory and create an .rvmrc for the gemset
$ cd awesome_rails_project
$ rvm --rvmrc 1.9.3@awesome_rails_project

# verify the rvmrc
$ cd ..; cd -

Rails 基本登录

def login
  if request.post?
    begin
      session[:user] = User.authenticate(params[:employee][:email], params[:employee][:password]).id
      redirect_to :controller => 'tickets', :action => 'list_open'
    rescue AuthenticationError => e
      flash[:warning] = "#{e}"
    end
  end
end

Rails 基本注销

def logout
  session[:user] = nil
  redirect_to :action => "login"
end

Rails 基本身份验证

def self.authenticate(email, password)
  user = find(:first, :conditions => ['email = ?', email])
  unless user.blank?
    if user.password_hash.nil? or Digest::SHA256.hexdigest(password + user.password_salt) == user.password_hash
      user.update_attributes(:last_login => Time.now.to_s(:db))
      user
    else
      raise AuthenticationError, "Invalid email and/or password"
    end
  else
    raise AuthenticationError, "Invalid email and/or password"
  end
end

Rails 我的登录

def login
    @page_title = 'Publisher login'
    if request.post? && publisher = Publisher.check(params[:publisher][:name], params[:publisher][:password])
      flash[:notice] = "#{publisher.name} was successfully logged in!"
      redirect_to :action => 'index'
    else
      flash.now[:notice] = "Please login!"
    end
  end

Rails 我把书加到购物车上

  def add
    book = Book.find(params[:id]) or raise ActiveRecord::RecordNotFound
    # Added by sending book object.
    flash[:cart_notice] = "'#{book.title}' was added!" if  @cart.add book
    redirect_to :action => 'index'
  end

Rails 我的最新书

  def self.latest
    find :all, :limit => 5, :order => 'books.id desc', :include => [:authors, :publisher]
  end

Rails 我在模型中添加了购物车

  def add(book)
    cur_item = cart_items.find_by_book_id(book.id)
    new_item = cart_items.new(:book_id => book.id, :price => book.price, :amount => 1)
    cur_item ? (cur_item.amount += 1; cur_item.save) : cart_items << new_item
  end

Rails Rails启动Webrick webserver

ruby script/server webrick

Rails 生成控制器

ruby script/generate controller Look