From 711c476c5d0c819d44e8d251d9d8d3700a86579d Mon Sep 17 00:00:00 2001 From: Jimmy Date: Thu, 10 Jul 2014 17:11:04 +0800 Subject: [PATCH 01/13] add admin/products --- app/assets/javascripts/admin/products.js.coffee | 3 +++ app/assets/stylesheets/admin/products.css.scss | 3 +++ app/controllers/admin/products_controller.rb | 2 ++ app/helpers/admin/products_helper.rb | 2 ++ test/controllers/admin/products_controller_test.rb | 7 +++++++ test/helpers/admin/products_helper_test.rb | 4 ++++ 6 files changed, 21 insertions(+) create mode 100644 app/assets/javascripts/admin/products.js.coffee create mode 100644 app/assets/stylesheets/admin/products.css.scss create mode 100644 app/controllers/admin/products_controller.rb create mode 100644 app/helpers/admin/products_helper.rb create mode 100644 test/controllers/admin/products_controller_test.rb create mode 100644 test/helpers/admin/products_helper_test.rb diff --git a/app/assets/javascripts/admin/products.js.coffee b/app/assets/javascripts/admin/products.js.coffee new file mode 100644 index 0000000..24f83d1 --- /dev/null +++ b/app/assets/javascripts/admin/products.js.coffee @@ -0,0 +1,3 @@ +# Place all the behaviors and hooks related to the matching controller here. +# All this logic will automatically be available in application.js. +# You can use CoffeeScript in this file: http://coffeescript.org/ diff --git a/app/assets/stylesheets/admin/products.css.scss b/app/assets/stylesheets/admin/products.css.scss new file mode 100644 index 0000000..da8969d --- /dev/null +++ b/app/assets/stylesheets/admin/products.css.scss @@ -0,0 +1,3 @@ +// Place all the styles related to the admin::products controller here. +// They will automatically be included in application.css. +// You can use Sass (SCSS) here: http://sass-lang.com/ diff --git a/app/controllers/admin/products_controller.rb b/app/controllers/admin/products_controller.rb new file mode 100644 index 0000000..b7b829c --- /dev/null +++ b/app/controllers/admin/products_controller.rb @@ -0,0 +1,2 @@ +class Admin::ProductsController < ApplicationController +end diff --git a/app/helpers/admin/products_helper.rb b/app/helpers/admin/products_helper.rb new file mode 100644 index 0000000..977a242 --- /dev/null +++ b/app/helpers/admin/products_helper.rb @@ -0,0 +1,2 @@ +module Admin::ProductsHelper +end diff --git a/test/controllers/admin/products_controller_test.rb b/test/controllers/admin/products_controller_test.rb new file mode 100644 index 0000000..508fe6b --- /dev/null +++ b/test/controllers/admin/products_controller_test.rb @@ -0,0 +1,7 @@ +require 'test_helper' + +class Admin::ProductsControllerTest < ActionController::TestCase + # test "the truth" do + # assert true + # end +end diff --git a/test/helpers/admin/products_helper_test.rb b/test/helpers/admin/products_helper_test.rb new file mode 100644 index 0000000..0b696b1 --- /dev/null +++ b/test/helpers/admin/products_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class Admin::ProductsHelperTest < ActionView::TestCase +end From ff5d375fa8004a93e007ba4d792147d18b6954e9 Mon Sep 17 00:00:00 2001 From: Jimmy Date: Thu, 10 Jul 2014 17:12:02 +0800 Subject: [PATCH 02/13] add admin prodcuts to routes --- config/routes.rb | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/config/routes.rb b/config/routes.rb index 3f66539..9306cd6 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,4 +1,8 @@ Rails.application.routes.draw do + + namespace :admin do + resources :products + end # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". From d8c1e157a664f2d0f02f2e4d6a4bf858942475a7 Mon Sep 17 00:00:00 2001 From: Jimmy Date: Thu, 10 Jul 2014 17:13:00 +0800 Subject: [PATCH 03/13] add product model --- app/models/product.rb | 2 ++ db/migrate/20140710091239_create_products.rb | 11 +++++++++++ test/fixtures/products.yml | 11 +++++++++++ test/models/product_test.rb | 7 +++++++ 4 files changed, 31 insertions(+) create mode 100644 app/models/product.rb create mode 100644 db/migrate/20140710091239_create_products.rb create mode 100644 test/fixtures/products.yml create mode 100644 test/models/product_test.rb diff --git a/app/models/product.rb b/app/models/product.rb new file mode 100644 index 0000000..077a819 --- /dev/null +++ b/app/models/product.rb @@ -0,0 +1,2 @@ +class Product < ActiveRecord::Base +end diff --git a/db/migrate/20140710091239_create_products.rb b/db/migrate/20140710091239_create_products.rb new file mode 100644 index 0000000..805c976 --- /dev/null +++ b/db/migrate/20140710091239_create_products.rb @@ -0,0 +1,11 @@ +class CreateProducts < ActiveRecord::Migration + def change + create_table :products do |t| + t.string :title + t.text :description + t.integer :quantity + + t.timestamps + end + end +end diff --git a/test/fixtures/products.yml b/test/fixtures/products.yml new file mode 100644 index 0000000..c3b9bc1 --- /dev/null +++ b/test/fixtures/products.yml @@ -0,0 +1,11 @@ +# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +one: + title: MyString + description: MyText + quantity: 1 + +two: + title: MyString + description: MyText + quantity: 1 diff --git a/test/models/product_test.rb b/test/models/product_test.rb new file mode 100644 index 0000000..211cdd0 --- /dev/null +++ b/test/models/product_test.rb @@ -0,0 +1,7 @@ +require 'test_helper' + +class ProductTest < ActiveSupport::TestCase + # test "the truth" do + # assert true + # end +end From c4dc95f64f646aff664f410447fcf66d945bb020 Mon Sep 17 00:00:00 2001 From: Jimmy Date: Thu, 10 Jul 2014 17:13:33 +0800 Subject: [PATCH 04/13] db:migrate --- db/schema.rb | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 db/schema.rb diff --git a/db/schema.rb b/db/schema.rb new file mode 100644 index 0000000..92a70d0 --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,24 @@ +# encoding: UTF-8 +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# Note that this schema.rb definition is the authoritative source for your +# database schema. If you need to create the application database on another +# system, you should be using db:schema:load, not running all the migrations +# from scratch. The latter is a flawed and unsustainable approach (the more migrations +# you'll amass, the slower it'll run and the greater likelihood for issues). +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema.define(version: 20140710091239) do + + create_table "products", force: true do |t| + t.string "title" + t.text "description" + t.integer "quantity" + t.datetime "created_at" + t.datetime "updated_at" + end + +end From 6f544714cd69ff4c45b9a9043c03d4b379e52fac Mon Sep 17 00:00:00 2001 From: Jimmy Date: Thu, 10 Jul 2014 17:29:54 +0800 Subject: [PATCH 05/13] add new&show method in controller --- app/views/admin/products/new.html.erb | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 app/views/admin/products/new.html.erb diff --git a/app/views/admin/products/new.html.erb b/app/views/admin/products/new.html.erb new file mode 100644 index 0000000..f5ce36b --- /dev/null +++ b/app/views/admin/products/new.html.erb @@ -0,0 +1,20 @@ + +<%= form_for [:admin, @product] do |form| %> +
+ <%= form.label("標題")%> + <%= form.text_field :title%> +
+ +
+ <%= form.label("敘述")%> + <%= form.text_field :description%> +
+ + +
+ <%= form.label("數量")%> + <%= form.text_field :quantity%> +
+ + <%= form.submit "submit", :disable_with=> 'Submiting....'%> +<%end%> \ No newline at end of file From 6fc4dd8a8decd5c9dc13051253b2ff96d9f78734 Mon Sep 17 00:00:00 2001 From: Jimmy Date: Thu, 10 Jul 2014 17:38:01 +0800 Subject: [PATCH 06/13] add index --- app/views/admin/products/index.html.erb | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 app/views/admin/products/index.html.erb diff --git a/app/views/admin/products/index.html.erb b/app/views/admin/products/index.html.erb new file mode 100644 index 0000000..c5592bd --- /dev/null +++ b/app/views/admin/products/index.html.erb @@ -0,0 +1,19 @@ + + + + + + + + + + <%@products.each do |product| %> + + + + + + + +<% end %> +
TitleDescriptionQuantity
<%= product.title %><%= product.description %><%= product.quantity %>
\ No newline at end of file From ae05833610b098e344672429b9dc3733ee30e70f Mon Sep 17 00:00:00 2001 From: Jimmy Date: Thu, 10 Jul 2014 18:06:27 +0800 Subject: [PATCH 07/13] add devise Gem and add auth --- app/views/admin/products/index.html.erb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/views/admin/products/index.html.erb b/app/views/admin/products/index.html.erb index c5592bd..f8b9ab5 100644 --- a/app/views/admin/products/index.html.erb +++ b/app/views/admin/products/index.html.erb @@ -1,4 +1,4 @@ - +<%= current_user.is_admin?%> From e24ef1e455ed0df6348a9f05911899bf781a186a Mon Sep 17 00:00:00 2001 From: Jimmy Date: Thu, 10 Jul 2014 19:27:50 +0800 Subject: [PATCH 08/13] add bootstrap gem --- Gemfile | 4 + Gemfile.lock | 14 + app/assets/stylesheets/application.css | 1 + app/controllers/admin/products_controller.rb | 29 ++ app/controllers/application_controller.rb | 5 + app/models/user.rb | 12 + app/views/admin/products/index.html.erb | 4 +- app/views/devise/confirmations/new.html.erb | 12 + .../mailer/confirmation_instructions.html.erb | 5 + .../reset_password_instructions.html.erb | 8 + .../mailer/unlock_instructions.html.erb | 7 + app/views/devise/passwords/edit.html.erb | 16 ++ app/views/devise/passwords/new.html.erb | 12 + app/views/devise/registrations/edit.html.erb | 29 ++ app/views/devise/registrations/new.html.erb | 18 ++ app/views/devise/sessions/new.html.erb | 17 ++ app/views/devise/shared/_links.erb | 25 ++ app/views/devise/unlocks/new.html.erb | 12 + app/views/layouts/_nav.html.erb | 38 +++ app/views/layouts/application.html.erb | 12 + config/environments/development.rb | 1 + config/initializers/devise.rb | 256 ++++++++++++++++++ config/locales/devise.en.yml | 59 ++++ config/routes.rb | 1 + .../20140710094043_devise_create_users.rb | 42 +++ .../20140710094701_add_is_admin_to_user.rb | 5 + db/schema.rb | 21 +- test/fixtures/users.yml | 11 + test/models/user_test.rb | 7 + 29 files changed, 680 insertions(+), 3 deletions(-) create mode 100644 app/models/user.rb create mode 100644 app/views/devise/confirmations/new.html.erb create mode 100644 app/views/devise/mailer/confirmation_instructions.html.erb create mode 100644 app/views/devise/mailer/reset_password_instructions.html.erb create mode 100644 app/views/devise/mailer/unlock_instructions.html.erb create mode 100644 app/views/devise/passwords/edit.html.erb create mode 100644 app/views/devise/passwords/new.html.erb create mode 100644 app/views/devise/registrations/edit.html.erb create mode 100644 app/views/devise/registrations/new.html.erb create mode 100644 app/views/devise/sessions/new.html.erb create mode 100644 app/views/devise/shared/_links.erb create mode 100644 app/views/devise/unlocks/new.html.erb create mode 100644 app/views/layouts/_nav.html.erb create mode 100644 config/initializers/devise.rb create mode 100644 config/locales/devise.en.yml create mode 100644 db/migrate/20140710094043_devise_create_users.rb create mode 100644 db/migrate/20140710094701_add_is_admin_to_user.rb create mode 100644 test/fixtures/users.yml create mode 100644 test/models/user_test.rb diff --git a/Gemfile b/Gemfile index fba3b4e..0342111 100644 --- a/Gemfile +++ b/Gemfile @@ -26,6 +26,10 @@ gem 'sdoc', '~> 0.4.0', group: :doc # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring', group: :development + +gem 'devise' +gem 'bootstrap-sass' + # Use ActiveModel has_secure_password # gem 'bcrypt', '~> 3.1.7' diff --git a/Gemfile.lock b/Gemfile.lock index 53538d9..c14dd7c 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -28,6 +28,9 @@ GEM thread_safe (~> 0.1) tzinfo (~> 1.1) arel (5.0.1.20140414130214) + bcrypt (3.1.7) + bootstrap-sass (3.2.0.0) + sass (~> 3.2) builder (3.2.2) coffee-rails (4.0.1) coffee-script (>= 2.2.0) @@ -36,6 +39,12 @@ GEM coffee-script-source execjs coffee-script-source (1.7.0) + devise (3.2.4) + bcrypt (~> 3.0) + orm_adapter (~> 0.1) + railties (>= 3.2.6, < 5) + thread_safe (~> 0.1) + warden (~> 1.2.3) erubis (2.7.0) execjs (2.2.0) hike (1.2.3) @@ -53,6 +62,7 @@ GEM mime-types (1.25.1) minitest (5.3.4) multi_json (1.10.1) + orm_adapter (0.5.0) polyglot (0.3.5) rack (1.5.2) rack-test (0.6.2) @@ -108,12 +118,16 @@ GEM uglifier (2.5.0) execjs (>= 0.3.0) json (>= 1.8.0) + warden (1.2.3) + rack (>= 1.0) PLATFORMS ruby DEPENDENCIES + bootstrap-sass coffee-rails (~> 4.0.0) + devise jbuilder (~> 2.0) jquery-rails rails (= 4.1.0) diff --git a/app/assets/stylesheets/application.css b/app/assets/stylesheets/application.css index a443db3..bcdb41c 100644 --- a/app/assets/stylesheets/application.css +++ b/app/assets/stylesheets/application.css @@ -12,4 +12,5 @@ * *= require_tree . *= require_self + *= require bootstrap */ diff --git a/app/controllers/admin/products_controller.rb b/app/controllers/admin/products_controller.rb index b7b829c..dbce1cd 100644 --- a/app/controllers/admin/products_controller.rb +++ b/app/controllers/admin/products_controller.rb @@ -1,2 +1,31 @@ class Admin::ProductsController < ApplicationController + + before_action :authenticate_user! + before_action :admin_required + + + def index + @products = Product.all + end + + def new + @product = Product.new + end + + def create + @product = Product.new(product_params) + if @product.save + redirect_to admin_products_path + else + render :new + end + end + + private + + def product_params + params.require(:product).permit(:title,:description,:quantity) + end + + end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index d83690e..7c1f1cb 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -2,4 +2,9 @@ class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception + + def admin_required + current_user.is_admin? + end + end diff --git a/app/models/user.rb b/app/models/user.rb new file mode 100644 index 0000000..83dc315 --- /dev/null +++ b/app/models/user.rb @@ -0,0 +1,12 @@ +class User < ActiveRecord::Base + # Include default devise modules. Others available are: + # :confirmable, :lockable, :timeoutable and :omniauthable + devise :database_authenticatable, :registerable, + :recoverable, :rememberable, :trackable, :validatable + + def is_admin? + is_admin + end + + +end diff --git a/app/views/admin/products/index.html.erb b/app/views/admin/products/index.html.erb index f8b9ab5..bbc35e6 100644 --- a/app/views/admin/products/index.html.erb +++ b/app/views/admin/products/index.html.erb @@ -1,5 +1,5 @@ -<%= current_user.is_admin?%> -
+ +
diff --git a/app/views/devise/confirmations/new.html.erb b/app/views/devise/confirmations/new.html.erb new file mode 100644 index 0000000..65ba288 --- /dev/null +++ b/app/views/devise/confirmations/new.html.erb @@ -0,0 +1,12 @@ +

Resend confirmation instructions

+ +<%= form_for(resource, as: resource_name, url: confirmation_path(resource_name), html: { method: :post }) do |f| %> + <%= devise_error_messages! %> + +
<%= f.label :email %>
+ <%= f.email_field :email, autofocus: true %>
+ +
<%= f.submit "Resend confirmation instructions" %>
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/mailer/confirmation_instructions.html.erb b/app/views/devise/mailer/confirmation_instructions.html.erb new file mode 100644 index 0000000..dc55f64 --- /dev/null +++ b/app/views/devise/mailer/confirmation_instructions.html.erb @@ -0,0 +1,5 @@ +

Welcome <%= @email %>!

+ +

You can confirm your account email through the link below:

+ +

<%= link_to 'Confirm my account', confirmation_url(@resource, confirmation_token: @token) %>

diff --git a/app/views/devise/mailer/reset_password_instructions.html.erb b/app/views/devise/mailer/reset_password_instructions.html.erb new file mode 100644 index 0000000..f667dc1 --- /dev/null +++ b/app/views/devise/mailer/reset_password_instructions.html.erb @@ -0,0 +1,8 @@ +

Hello <%= @resource.email %>!

+ +

Someone has requested a link to change your password. You can do this through the link below.

+ +

<%= link_to 'Change my password', edit_password_url(@resource, reset_password_token: @token) %>

+ +

If you didn't request this, please ignore this email.

+

Your password won't change until you access the link above and create a new one.

diff --git a/app/views/devise/mailer/unlock_instructions.html.erb b/app/views/devise/mailer/unlock_instructions.html.erb new file mode 100644 index 0000000..41e148b --- /dev/null +++ b/app/views/devise/mailer/unlock_instructions.html.erb @@ -0,0 +1,7 @@ +

Hello <%= @resource.email %>!

+ +

Your account has been locked due to an excessive number of unsuccessful sign in attempts.

+ +

Click the link below to unlock your account:

+ +

<%= link_to 'Unlock my account', unlock_url(@resource, unlock_token: @token) %>

diff --git a/app/views/devise/passwords/edit.html.erb b/app/views/devise/passwords/edit.html.erb new file mode 100644 index 0000000..5535098 --- /dev/null +++ b/app/views/devise/passwords/edit.html.erb @@ -0,0 +1,16 @@ +

Change your password

+ +<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :put }) do |f| %> + <%= devise_error_messages! %> + <%= f.hidden_field :reset_password_token %> + +
<%= f.label :password, "New password" %>
+ <%= f.password_field :password, autofocus: true, autocomplete: "off" %>
+ +
<%= f.label :password_confirmation, "Confirm new password" %>
+ <%= f.password_field :password_confirmation, autocomplete: "off" %>
+ +
<%= f.submit "Change my password" %>
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/passwords/new.html.erb b/app/views/devise/passwords/new.html.erb new file mode 100644 index 0000000..ea1d46e --- /dev/null +++ b/app/views/devise/passwords/new.html.erb @@ -0,0 +1,12 @@ +

Forgot your password?

+ +<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %> + <%= devise_error_messages! %> + +
<%= f.label :email %>
+ <%= f.email_field :email, autofocus: true %>
+ +
<%= f.submit "Send me reset password instructions" %>
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/registrations/edit.html.erb b/app/views/devise/registrations/edit.html.erb new file mode 100644 index 0000000..808d62c --- /dev/null +++ b/app/views/devise/registrations/edit.html.erb @@ -0,0 +1,29 @@ +

Edit <%= resource_name.to_s.humanize %>

+ +<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %> + <%= devise_error_messages! %> + +
<%= f.label :email %>
+ <%= f.email_field :email, autofocus: true %>
+ + <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %> +
Currently waiting confirmation for: <%= resource.unconfirmed_email %>
+ <% end %> + +
<%= f.label :password %> (leave blank if you don't want to change it)
+ <%= f.password_field :password, autocomplete: "off" %>
+ +
<%= f.label :password_confirmation %>
+ <%= f.password_field :password_confirmation, autocomplete: "off" %>
+ +
<%= f.label :current_password %> (we need your current password to confirm your changes)
+ <%= f.password_field :current_password, autocomplete: "off" %>
+ +
<%= f.submit "Update" %>
+<% end %> + +

Cancel my account

+ +

Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %>

+ +<%= link_to "Back", :back %> diff --git a/app/views/devise/registrations/new.html.erb b/app/views/devise/registrations/new.html.erb new file mode 100644 index 0000000..234de91 --- /dev/null +++ b/app/views/devise/registrations/new.html.erb @@ -0,0 +1,18 @@ +

Sign up

+ +<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> + <%= devise_error_messages! %> + +
<%= f.label :email %>
+ <%= f.email_field :email, autofocus: true %>
+ +
<%= f.label :password %>
+ <%= f.password_field :password, autocomplete: "off" %>
+ +
<%= f.label :password_confirmation %>
+ <%= f.password_field :password_confirmation, autocomplete: "off" %>
+ +
<%= f.submit "Sign up" %>
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/sessions/new.html.erb b/app/views/devise/sessions/new.html.erb new file mode 100644 index 0000000..f151ac1 --- /dev/null +++ b/app/views/devise/sessions/new.html.erb @@ -0,0 +1,17 @@ +

Sign in

+ +<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %> +
<%= f.label :email %>
+ <%= f.email_field :email, autofocus: true %>
+ +
<%= f.label :password %>
+ <%= f.password_field :password, autocomplete: "off" %>
+ + <% if devise_mapping.rememberable? -%> +
<%= f.check_box :remember_me %> <%= f.label :remember_me %>
+ <% end -%> + +
<%= f.submit "Sign in" %>
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/shared/_links.erb b/app/views/devise/shared/_links.erb new file mode 100644 index 0000000..d84bdde --- /dev/null +++ b/app/views/devise/shared/_links.erb @@ -0,0 +1,25 @@ +<%- if controller_name != 'sessions' %> + <%= link_to "Sign in", new_session_path(resource_name) %>
+<% end -%> + +<%- if devise_mapping.registerable? && controller_name != 'registrations' %> + <%= link_to "Sign up", new_registration_path(resource_name) %>
+<% end -%> + +<%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %> + <%= link_to "Forgot your password?", new_password_path(resource_name) %>
+<% end -%> + +<%- if devise_mapping.confirmable? && controller_name != 'confirmations' %> + <%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %>
+<% end -%> + +<%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %> + <%= link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name) %>
+<% end -%> + +<%- if devise_mapping.omniauthable? %> + <%- resource_class.omniauth_providers.each do |provider| %> + <%= link_to "Sign in with #{provider.to_s.titleize}", omniauth_authorize_path(resource_name, provider) %>
+ <% end -%> +<% end -%> diff --git a/app/views/devise/unlocks/new.html.erb b/app/views/devise/unlocks/new.html.erb new file mode 100644 index 0000000..6fb5612 --- /dev/null +++ b/app/views/devise/unlocks/new.html.erb @@ -0,0 +1,12 @@ +

Resend unlock instructions

+ +<%= form_for(resource, as: resource_name, url: unlock_path(resource_name), html: { method: :post }) do |f| %> + <%= devise_error_messages! %> + +
<%= f.label :email %>
+ <%= f.email_field :email, autofocus: true %>
+ +
<%= f.submit "Resend unlock instructions" %>
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/layouts/_nav.html.erb b/app/views/layouts/_nav.html.erb new file mode 100644 index 0000000..d43964a --- /dev/null +++ b/app/views/layouts/_nav.html.erb @@ -0,0 +1,38 @@ + + diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index da9769d..8bb01ae 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -8,7 +8,19 @@ +<%= render 'layouts/nav'%> +
+

<%= notice %>

+

<%= alert %>

+ +<% if !current_user %> + <%= link_to("登入", new_user_session_path)%> +<% else %> + <%= link_to("登出",destroy_user_session_path, :method =>:delete )%> +<% end %> + <%= yield %> +
diff --git a/config/environments/development.rb b/config/environments/development.rb index ddf0e90..38152b3 100644 --- a/config/environments/development.rb +++ b/config/environments/development.rb @@ -34,4 +34,5 @@ # Raises error for missing translations # config.action_view.raise_on_missing_translations = true + config.action_mailer.default_url_options = { host: 'localhost:3000' } end diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb new file mode 100644 index 0000000..49f7b5b --- /dev/null +++ b/config/initializers/devise.rb @@ -0,0 +1,256 @@ +# Use this hook to configure devise mailer, warden hooks and so forth. +# Many of these configuration options can be set straight in your model. +Devise.setup do |config| + # The secret key used by Devise. Devise uses this key to generate + # random tokens. Changing this key will render invalid all existing + # confirmation, reset password and unlock tokens in the database. + # config.secret_key = 'd8161df8a6330e1a3958379ae04568a33696daf1937a1d31b68404b844acc0e54c797e5cc7d1f4f8b3864d389e88c89f27e19a928c9707f61f9d557f183d52b1' + + # ==> Mailer Configuration + # Configure the e-mail address which will be shown in Devise::Mailer, + # note that it will be overwritten if you use your own mailer class + # with default "from" parameter. + config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com' + + # Configure the class responsible to send e-mails. + # config.mailer = 'Devise::Mailer' + + # ==> ORM configuration + # Load and configure the ORM. Supports :active_record (default) and + # :mongoid (bson_ext recommended) by default. Other ORMs may be + # available as additional gems. + require 'devise/orm/active_record' + + # ==> Configuration for any authentication mechanism + # Configure which keys are used when authenticating a user. The default is + # just :email. You can configure it to use [:username, :subdomain], so for + # authenticating a user, both parameters are required. Remember that those + # parameters are used only when authenticating and not when retrieving from + # session. If you need permissions, you should implement that in a before filter. + # You can also supply a hash where the value is a boolean determining whether + # or not authentication should be aborted when the value is not present. + # config.authentication_keys = [ :email ] + + # Configure parameters from the request object used for authentication. Each entry + # given should be a request method and it will automatically be passed to the + # find_for_authentication method and considered in your model lookup. For instance, + # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. + # The same considerations mentioned for authentication_keys also apply to request_keys. + # config.request_keys = [] + + # Configure which authentication keys should be case-insensitive. + # These keys will be downcased upon creating or modifying a user and when used + # to authenticate or find a user. Default is :email. + config.case_insensitive_keys = [ :email ] + + # Configure which authentication keys should have whitespace stripped. + # These keys will have whitespace before and after removed upon creating or + # modifying a user and when used to authenticate or find a user. Default is :email. + config.strip_whitespace_keys = [ :email ] + + # Tell if authentication through request.params is enabled. True by default. + # It can be set to an array that will enable params authentication only for the + # given strategies, for example, `config.params_authenticatable = [:database]` will + # enable it only for database (email + password) authentication. + # config.params_authenticatable = true + + # Tell if authentication through HTTP Auth is enabled. False by default. + # It can be set to an array that will enable http authentication only for the + # given strategies, for example, `config.http_authenticatable = [:database]` will + # enable it only for database authentication. The supported strategies are: + # :database = Support basic authentication with authentication key + password + # config.http_authenticatable = false + + # If http headers should be returned for AJAX requests. True by default. + # config.http_authenticatable_on_xhr = true + + # The realm used in Http Basic Authentication. 'Application' by default. + # config.http_authentication_realm = 'Application' + + # It will change confirmation, password recovery and other workflows + # to behave the same regardless if the e-mail provided was right or wrong. + # Does not affect registerable. + # config.paranoid = true + + # By default Devise will store the user in session. You can skip storage for + # particular strategies by setting this option. + # Notice that if you are skipping storage for all authentication paths, you + # may want to disable generating routes to Devise's sessions controller by + # passing skip: :sessions to `devise_for` in your config/routes.rb + config.skip_session_storage = [:http_auth] + + # By default, Devise cleans up the CSRF token on authentication to + # avoid CSRF token fixation attacks. This means that, when using AJAX + # requests for sign in and sign up, you need to get a new CSRF token + # from the server. You can disable this option at your own risk. + # config.clean_up_csrf_token_on_authentication = true + + # ==> Configuration for :database_authenticatable + # For bcrypt, this is the cost for hashing the password and defaults to 10. If + # using other encryptors, it sets how many times you want the password re-encrypted. + # + # Limiting the stretches to just one in testing will increase the performance of + # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use + # a value less than 10 in other environments. Note that, for bcrypt (the default + # encryptor), the cost increases exponentially with the number of stretches (e.g. + # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). + config.stretches = Rails.env.test? ? 1 : 10 + + # Setup a pepper to generate the encrypted password. + # config.pepper = '9351a5e18e09816b7210c4a7162b78d8d0037e81e8c4421b75533a76f5296c75a4f8c287da88f1a3219f6479502d8179d4d9c1a04c8a668e4d4ba9de3d1b653b' + + # ==> Configuration for :confirmable + # A period that the user is allowed to access the website even without + # confirming their account. For instance, if set to 2.days, the user will be + # able to access the website for two days without confirming their account, + # access will be blocked just in the third day. Default is 0.days, meaning + # the user cannot access the website without confirming their account. + # config.allow_unconfirmed_access_for = 2.days + + # A period that the user is allowed to confirm their account before their + # token becomes invalid. For example, if set to 3.days, the user can confirm + # their account within 3 days after the mail was sent, but on the fourth day + # their account can't be confirmed with the token any more. + # Default is nil, meaning there is no restriction on how long a user can take + # before confirming their account. + # config.confirm_within = 3.days + + # If true, requires any email changes to be confirmed (exactly the same way as + # initial account confirmation) to be applied. Requires additional unconfirmed_email + # db field (see migrations). Until confirmed, new email is stored in + # unconfirmed_email column, and copied to email column on successful confirmation. + config.reconfirmable = true + + # Defines which key will be used when confirming an account + # config.confirmation_keys = [ :email ] + + # ==> Configuration for :rememberable + # The time the user will be remembered without asking for credentials again. + # config.remember_for = 2.weeks + + # If true, extends the user's remember period when remembered via cookie. + # config.extend_remember_period = false + + # Options to be passed to the created cookie. For instance, you can set + # secure: true in order to force SSL only cookies. + # config.rememberable_options = {} + + # ==> Configuration for :validatable + # Range for password length. + config.password_length = 8..128 + + # Email regex used to validate email formats. It simply asserts that + # one (and only one) @ exists in the given string. This is mainly + # to give user feedback and not to assert the e-mail validity. + # config.email_regexp = /\A[^@]+@[^@]+\z/ + + # ==> Configuration for :timeoutable + # The time you want to timeout the user session without activity. After this + # time the user will be asked for credentials again. Default is 30 minutes. + # config.timeout_in = 30.minutes + + # If true, expires auth token on session timeout. + # config.expire_auth_token_on_timeout = false + + # ==> Configuration for :lockable + # Defines which strategy will be used to lock an account. + # :failed_attempts = Locks an account after a number of failed attempts to sign in. + # :none = No lock strategy. You should handle locking by yourself. + # config.lock_strategy = :failed_attempts + + # Defines which key will be used when locking and unlocking an account + # config.unlock_keys = [ :email ] + + # Defines which strategy will be used to unlock an account. + # :email = Sends an unlock link to the user email + # :time = Re-enables login after a certain amount of time (see :unlock_in below) + # :both = Enables both strategies + # :none = No unlock strategy. You should handle unlocking by yourself. + # config.unlock_strategy = :both + + # Number of authentication tries before locking an account if lock_strategy + # is failed attempts. + # config.maximum_attempts = 20 + + # Time interval to unlock the account if :time is enabled as unlock_strategy. + # config.unlock_in = 1.hour + + # Warn on the last attempt before the account is locked. + # config.last_attempt_warning = false + + # ==> Configuration for :recoverable + # + # Defines which key will be used when recovering the password for an account + # config.reset_password_keys = [ :email ] + + # Time interval you can reset your password with a reset password key. + # Don't put a too small interval or your users won't have the time to + # change their passwords. + config.reset_password_within = 6.hours + + # ==> Configuration for :encryptable + # Allow you to use another encryption algorithm besides bcrypt (default). You can use + # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1, + # :authlogic_sha512 (then you should set stretches above to 20 for default behavior) + # and :restful_authentication_sha1 (then you should set stretches to 10, and copy + # REST_AUTH_SITE_KEY to pepper). + # + # Require the `devise-encryptable` gem when using anything other than bcrypt + # config.encryptor = :sha512 + + # ==> Scopes configuration + # Turn scoped views on. Before rendering "sessions/new", it will first check for + # "users/sessions/new". It's turned off by default because it's slower if you + # are using only default views. + # config.scoped_views = false + + # Configure the default scope given to Warden. By default it's the first + # devise role declared in your routes (usually :user). + # config.default_scope = :user + + # Set this configuration to false if you want /users/sign_out to sign out + # only the current scope. By default, Devise signs out all scopes. + # config.sign_out_all_scopes = true + + # ==> Navigation configuration + # Lists the formats that should be treated as navigational. Formats like + # :html, should redirect to the sign in page when the user does not have + # access, but formats like :xml or :json, should return 401. + # + # If you have any extra navigational formats, like :iphone or :mobile, you + # should add them to the navigational formats lists. + # + # The "*/*" below is required to match Internet Explorer requests. + # config.navigational_formats = ['*/*', :html] + + # The default HTTP method used to sign out a resource. Default is :delete. + config.sign_out_via = :delete + + # ==> OmniAuth + # Add a new OmniAuth provider. Check the wiki for more information on setting + # up on your models and hooks. + # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' + + # ==> Warden configuration + # If you want to use other strategies, that are not supported by Devise, or + # change the failure app, you can configure them inside the config.warden block. + # + # config.warden do |manager| + # manager.intercept_401 = false + # manager.default_strategies(scope: :user).unshift :some_external_strategy + # end + + # ==> Mountable engine configurations + # When using Devise inside an engine, let's call it `MyEngine`, and this engine + # is mountable, there are some extra configurations to be taken into account. + # The following options are available, assuming the engine is mounted as: + # + # mount MyEngine, at: '/my_engine' + # + # The router that invoked `devise_for`, in the example above, would be: + # config.router_name = :my_engine + # + # When using omniauth, Devise cannot automatically set Omniauth path, + # so you need to do it manually. For the users scope, it would be: + # config.omniauth_path_prefix = '/my_engine/users/auth' +end diff --git a/config/locales/devise.en.yml b/config/locales/devise.en.yml new file mode 100644 index 0000000..abccdb0 --- /dev/null +++ b/config/locales/devise.en.yml @@ -0,0 +1,59 @@ +# Additional translations at https://github.com/plataformatec/devise/wiki/I18n + +en: + devise: + confirmations: + confirmed: "Your account was successfully confirmed." + send_instructions: "You will receive an email with instructions about how to confirm your account in a few minutes." + send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions about how to confirm your account in a few minutes." + failure: + already_authenticated: "You are already signed in." + inactive: "Your account is not activated yet." + invalid: "Invalid email or password." + locked: "Your account is locked." + last_attempt: "You have one more attempt before your account will be locked." + not_found_in_database: "Invalid email or password." + timeout: "Your session expired. Please sign in again to continue." + unauthenticated: "You need to sign in or sign up before continuing." + unconfirmed: "You have to confirm your account before continuing." + mailer: + confirmation_instructions: + subject: "Confirmation instructions" + reset_password_instructions: + subject: "Reset password instructions" + unlock_instructions: + subject: "Unlock Instructions" + omniauth_callbacks: + failure: "Could not authenticate you from %{kind} because \"%{reason}\"." + success: "Successfully authenticated from %{kind} account." + passwords: + no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided." + send_instructions: "You will receive an email with instructions on how to reset your password in a few minutes." + send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes." + updated: "Your password was changed successfully. You are now signed in." + updated_not_active: "Your password was changed successfully." + registrations: + destroyed: "Bye! Your account was successfully cancelled. We hope to see you again soon." + signed_up: "Welcome! You have signed up successfully." + signed_up_but_inactive: "You have signed up successfully. However, we could not sign you in because your account is not yet activated." + signed_up_but_locked: "You have signed up successfully. However, we could not sign you in because your account is locked." + signed_up_but_unconfirmed: "A message with a confirmation link has been sent to your email address. Please open the link to activate your account." + update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and click on the confirm link to finalize confirming your new email address." + updated: "You updated your account successfully." + sessions: + signed_in: "Signed in successfully." + signed_out: "Signed out successfully." + unlocks: + send_instructions: "You will receive an email with instructions about how to unlock your account in a few minutes." + send_paranoid_instructions: "If your account exists, you will receive an email with instructions about how to unlock it in a few minutes." + unlocked: "Your account has been unlocked successfully. Please sign in to continue." + errors: + messages: + already_confirmed: "was already confirmed, please try signing in" + confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one" + expired: "has expired, please request a new one" + not_found: "not found" + not_locked: "was not locked" + not_saved: + one: "1 error prohibited this %{resource} from being saved:" + other: "%{count} errors prohibited this %{resource} from being saved:" diff --git a/config/routes.rb b/config/routes.rb index 9306cd6..e8ec128 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,5 +1,6 @@ Rails.application.routes.draw do + devise_for :users namespace :admin do resources :products end diff --git a/db/migrate/20140710094043_devise_create_users.rb b/db/migrate/20140710094043_devise_create_users.rb new file mode 100644 index 0000000..cf497c2 --- /dev/null +++ b/db/migrate/20140710094043_devise_create_users.rb @@ -0,0 +1,42 @@ +class DeviseCreateUsers < ActiveRecord::Migration + def change + create_table(:users) do |t| + ## Database authenticatable + t.string :email, null: false, default: "" + t.string :encrypted_password, null: false, default: "" + + ## Recoverable + t.string :reset_password_token + t.datetime :reset_password_sent_at + + ## Rememberable + t.datetime :remember_created_at + + ## Trackable + t.integer :sign_in_count, default: 0, null: false + t.datetime :current_sign_in_at + t.datetime :last_sign_in_at + t.string :current_sign_in_ip + t.string :last_sign_in_ip + + ## Confirmable + # t.string :confirmation_token + # t.datetime :confirmed_at + # t.datetime :confirmation_sent_at + # t.string :unconfirmed_email # Only if using reconfirmable + + ## Lockable + # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts + # t.string :unlock_token # Only if unlock strategy is :email or :both + # t.datetime :locked_at + + + t.timestamps + end + + add_index :users, :email, unique: true + add_index :users, :reset_password_token, unique: true + # add_index :users, :confirmation_token, unique: true + # add_index :users, :unlock_token, unique: true + end +end diff --git a/db/migrate/20140710094701_add_is_admin_to_user.rb b/db/migrate/20140710094701_add_is_admin_to_user.rb new file mode 100644 index 0000000..6146e07 --- /dev/null +++ b/db/migrate/20140710094701_add_is_admin_to_user.rb @@ -0,0 +1,5 @@ +class AddIsAdminToUser < ActiveRecord::Migration + def change + add_column :users ,:is_admin, :boolean, :default=>false + end +end diff --git a/db/schema.rb b/db/schema.rb index 92a70d0..58e6990 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -11,7 +11,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 20140710091239) do +ActiveRecord::Schema.define(version: 20140710094701) do create_table "products", force: true do |t| t.string "title" @@ -21,4 +21,23 @@ t.datetime "updated_at" end + create_table "users", force: true do |t| + t.string "email", default: "", null: false + t.string "encrypted_password", default: "", null: false + t.string "reset_password_token" + t.datetime "reset_password_sent_at" + t.datetime "remember_created_at" + t.integer "sign_in_count", default: 0, null: false + t.datetime "current_sign_in_at" + t.datetime "last_sign_in_at" + t.string "current_sign_in_ip" + t.string "last_sign_in_ip" + t.datetime "created_at" + t.datetime "updated_at" + t.boolean "is_admin", default: false + end + + add_index "users", ["email"], name: "index_users_on_email", unique: true + add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true + end diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml new file mode 100644 index 0000000..937a0c0 --- /dev/null +++ b/test/fixtures/users.yml @@ -0,0 +1,11 @@ +# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +# This model initially had no columns defined. If you add columns to the +# model remove the '{}' from the fixture names and add the columns immediately +# below each fixture, per the syntax in the comments below +# +one: {} +# column: value +# +two: {} +# column: value diff --git a/test/models/user_test.rb b/test/models/user_test.rb new file mode 100644 index 0000000..82f61e0 --- /dev/null +++ b/test/models/user_test.rb @@ -0,0 +1,7 @@ +require 'test_helper' + +class UserTest < ActiveSupport::TestCase + # test "the truth" do + # assert true + # end +end From 74b1516b56420f954c1b5ab9e0f377e6117c193b Mon Sep 17 00:00:00 2001 From: Jimmy Date: Thu, 10 Jul 2014 19:43:48 +0800 Subject: [PATCH 09/13] add carrierwave Gem and mini_magick Gem --- Gemfile | 3 ++ Gemfile.lock | 10 ++++ app/controllers/admin/products_controller.rb | 2 +- app/models/product.rb | 1 + app/uploaders/image_uploader.rb | 51 +++++++++++++++++++ app/views/admin/products/index.html.erb | 2 + app/views/admin/products/new.html.erb | 5 ++ .../20140710113528_add_image_to_products.rb | 5 ++ db/schema.rb | 3 +- 9 files changed, 80 insertions(+), 2 deletions(-) create mode 100644 app/uploaders/image_uploader.rb create mode 100644 db/migrate/20140710113528_add_image_to_products.rb diff --git a/Gemfile b/Gemfile index 0342111..7b4f962 100644 --- a/Gemfile +++ b/Gemfile @@ -30,6 +30,9 @@ gem 'spring', group: :development gem 'devise' gem 'bootstrap-sass' +gem 'carrierwave' +gem "mini_magick" + # Use ActiveModel has_secure_password # gem 'bcrypt', '~> 3.1.7' diff --git a/Gemfile.lock b/Gemfile.lock index c14dd7c..bf98a1f 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -32,6 +32,11 @@ GEM bootstrap-sass (3.2.0.0) sass (~> 3.2) builder (3.2.2) + carrierwave (0.10.0) + activemodel (>= 3.2.0) + activesupport (>= 3.2.0) + json (>= 1.7) + mime-types (>= 1.16) coffee-rails (4.0.1) coffee-script (>= 2.2.0) railties (>= 4.0.0, < 5.0) @@ -60,6 +65,8 @@ GEM mime-types (~> 1.16) treetop (~> 1.4.8) mime-types (1.25.1) + mini_magick (3.7.0) + subexec (~> 0.2.1) minitest (5.3.4) multi_json (1.10.1) orm_adapter (0.5.0) @@ -105,6 +112,7 @@ GEM activesupport (>= 3.0) sprockets (~> 2.8) sqlite3 (1.3.9) + subexec (0.2.3) thor (0.19.1) thread_safe (0.3.4) tilt (1.4.1) @@ -126,10 +134,12 @@ PLATFORMS DEPENDENCIES bootstrap-sass + carrierwave coffee-rails (~> 4.0.0) devise jbuilder (~> 2.0) jquery-rails + mini_magick rails (= 4.1.0) sass-rails (~> 4.0.3) sdoc (~> 0.4.0) diff --git a/app/controllers/admin/products_controller.rb b/app/controllers/admin/products_controller.rb index dbce1cd..caa2a23 100644 --- a/app/controllers/admin/products_controller.rb +++ b/app/controllers/admin/products_controller.rb @@ -24,7 +24,7 @@ def create private def product_params - params.require(:product).permit(:title,:description,:quantity) + params.require(:product).permit(:title,:description,:quantity, :image) end diff --git a/app/models/product.rb b/app/models/product.rb index 077a819..c745566 100644 --- a/app/models/product.rb +++ b/app/models/product.rb @@ -1,2 +1,3 @@ class Product < ActiveRecord::Base + mount_uploader :image , ImagicUploader end diff --git a/app/uploaders/image_uploader.rb b/app/uploaders/image_uploader.rb new file mode 100644 index 0000000..2fc27d0 --- /dev/null +++ b/app/uploaders/image_uploader.rb @@ -0,0 +1,51 @@ +# encoding: utf-8 + +class ImageUploader < CarrierWave::Uploader::Base + + # Include RMagick or MiniMagick support: + # include CarrierWave::RMagick + # include CarrierWave::MiniMagick + + # Choose what kind of storage to use for this uploader: + storage :file + # storage :fog + + # Override the directory where uploaded files will be stored. + # This is a sensible default for uploaders that are meant to be mounted: + def store_dir + "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" + end + + # Provide a default URL as a default if there hasn't been a file uploaded: + # def default_url + # # For Rails 3.1+ asset pipeline compatibility: + # # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_')) + # + # "/images/fallback/" + [version_name, "default.png"].compact.join('_') + # end + + # Process files as they are uploaded: + # process :scale => [200, 300] + # + # def scale(width, height) + # # do something + # end + + # Create different versions of your uploaded files: + # version :thumb do + # process :resize_to_fit => [50, 50] + # end + + # Add a white list of extensions which are allowed to be uploaded. + # For images you might use something like this: + # def extension_white_list + # %w(jpg jpeg gif png) + # end + + # Override the filename of the uploaded files: + # Avoid using model.id or version_name here, see uploader/store.rb for details. + # def filename + # "something.jpg" if original_filename + # end + +end diff --git a/app/views/admin/products/index.html.erb b/app/views/admin/products/index.html.erb index bbc35e6..63d478f 100644 --- a/app/views/admin/products/index.html.erb +++ b/app/views/admin/products/index.html.erb @@ -5,6 +5,7 @@ + <%@products.each do |product| %> @@ -13,6 +14,7 @@ + <% end %> diff --git a/app/views/admin/products/new.html.erb b/app/views/admin/products/new.html.erb index f5ce36b..d05c1bd 100644 --- a/app/views/admin/products/new.html.erb +++ b/app/views/admin/products/new.html.erb @@ -16,5 +16,10 @@ <%= form.text_field :quantity%> +
+ <%= form.label("上傳")%> + <%= form.file_field :image%> +
+ <%= form.submit "submit", :disable_with=> 'Submiting....'%> <%end%> \ No newline at end of file diff --git a/db/migrate/20140710113528_add_image_to_products.rb b/db/migrate/20140710113528_add_image_to_products.rb new file mode 100644 index 0000000..a9b81ed --- /dev/null +++ b/db/migrate/20140710113528_add_image_to_products.rb @@ -0,0 +1,5 @@ +class AddImageToProducts < ActiveRecord::Migration + def change + add_column :products, :image , :string + end +end diff --git a/db/schema.rb b/db/schema.rb index 58e6990..64d6fa6 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -11,7 +11,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 20140710094701) do +ActiveRecord::Schema.define(version: 20140710113528) do create_table "products", force: true do |t| t.string "title" @@ -19,6 +19,7 @@ t.integer "quantity" t.datetime "created_at" t.datetime "updated_at" + t.string "image" end create_table "users", force: true do |t| From f7d83b9f574637c77b3eca8be481a90bce17f188 Mon Sep 17 00:00:00 2001 From: Jimmy Date: Thu, 10 Jul 2014 21:38:55 +0800 Subject: [PATCH 10/13] image upload and navigation layout --- app/controllers/admin/products_controller.rb | 5 +++ app/models/product.rb | 4 ++- app/uploaders/image_uploader.rb | 24 ++++++++++--- app/views/admin/products/index.html.erb | 33 ++++++++---------- app/views/admin/products/show.html.erb | 15 ++++++++ app/views/layouts/_nav.html.erb | 30 ++++++---------- app/views/layouts/application.html.erb | 6 ---- config/routes.rb | 3 ++ .../image/1/_____2014-07-10___5.03.50.png | Bin 0 -> 164199 bytes .../1/thumb______2014-07-10___5.03.50.png | Bin 0 -> 6167 bytes .../image/2/_____2014-07-10___5.03.50.png | Bin 0 -> 164199 bytes .../uploads/product/image/2/md_unassign.png | Bin 0 -> 79618 bytes .../uploads/product/image/2/sm_unassign.png | Bin 0 -> 22821 bytes .../product/image/2/square_unassign.png | Bin 0 -> 22884 bytes public/uploads/product/image/2/unassign.png | Bin 0 -> 63216 bytes .../image/3/_____2014-07-01___11.04.17.png | Bin 0 -> 62387 bytes .../image/3/_____2014-07-10___4.07.41.png | Bin 0 -> 164639 bytes .../image/3/md______2014-07-10___4.07.41.png | Bin 0 -> 105636 bytes .../image/3/sm______2014-07-10___4.07.41.png | Bin 0 -> 45384 bytes .../3/square______2014-07-10___4.07.41.png | Bin 0 -> 48353 bytes .../3/thumb______2014-07-01___11.04.17.png | Bin 0 -> 2512 bytes 21 files changed, 71 insertions(+), 49 deletions(-) create mode 100644 app/views/admin/products/show.html.erb create mode 100644 public/uploads/product/image/1/_____2014-07-10___5.03.50.png create mode 100644 public/uploads/product/image/1/thumb______2014-07-10___5.03.50.png create mode 100644 public/uploads/product/image/2/_____2014-07-10___5.03.50.png create mode 100644 public/uploads/product/image/2/md_unassign.png create mode 100644 public/uploads/product/image/2/sm_unassign.png create mode 100644 public/uploads/product/image/2/square_unassign.png create mode 100644 public/uploads/product/image/2/unassign.png create mode 100644 public/uploads/product/image/3/_____2014-07-01___11.04.17.png create mode 100644 public/uploads/product/image/3/_____2014-07-10___4.07.41.png create mode 100644 public/uploads/product/image/3/md______2014-07-10___4.07.41.png create mode 100644 public/uploads/product/image/3/sm______2014-07-10___4.07.41.png create mode 100644 public/uploads/product/image/3/square______2014-07-10___4.07.41.png create mode 100644 public/uploads/product/image/3/thumb______2014-07-01___11.04.17.png diff --git a/app/controllers/admin/products_controller.rb b/app/controllers/admin/products_controller.rb index caa2a23..fd00bc2 100644 --- a/app/controllers/admin/products_controller.rb +++ b/app/controllers/admin/products_controller.rb @@ -12,6 +12,11 @@ def new @product = Product.new end + def show + @product = Product.find(params[:id]) + end + + def create @product = Product.new(product_params) if @product.save diff --git a/app/models/product.rb b/app/models/product.rb index c745566..9afd99e 100644 --- a/app/models/product.rb +++ b/app/models/product.rb @@ -1,3 +1,5 @@ class Product < ActiveRecord::Base - mount_uploader :image , ImagicUploader + mount_uploader :image , ImageUploader + + end diff --git a/app/uploaders/image_uploader.rb b/app/uploaders/image_uploader.rb index 2fc27d0..987fe1b 100644 --- a/app/uploaders/image_uploader.rb +++ b/app/uploaders/image_uploader.rb @@ -4,7 +4,7 @@ class ImageUploader < CarrierWave::Uploader::Base # Include RMagick or MiniMagick support: # include CarrierWave::RMagick - # include CarrierWave::MiniMagick + include CarrierWave::MiniMagick # Choose what kind of storage to use for this uploader: storage :file @@ -16,6 +16,9 @@ def store_dir "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end + + + # Provide a default URL as a default if there hasn't been a file uploaded: # def default_url # # For Rails 3.1+ asset pipeline compatibility: @@ -32,9 +35,22 @@ def store_dir # end # Create different versions of your uploaded files: - # version :thumb do - # process :resize_to_fit => [50, 50] - # end + # version :thumb do + # process :resize_to_fit => [150, 150] + # end + + version :md do + process resize_to_fit: [700, 500] + end + + version :sm, from_version: :md do + process resize_to_fit: [300, 300] + end + + version :square, from_version: :sm do + process resize_to_fill: [220, 220] + end + # Add a white list of extensions which are allowed to be uploaded. # For images you might use something like this: diff --git a/app/views/admin/products/index.html.erb b/app/views/admin/products/index.html.erb index 63d478f..ac96f9c 100644 --- a/app/views/admin/products/index.html.erb +++ b/app/views/admin/products/index.html.erb @@ -1,21 +1,18 @@ -
Title Title Description QuantityImage]
<%= product.title %> <%= product.description %> <%= product.quantity %><%= product.image.url.to_s%>
- - - - - - - - <%@products.each do |product| %> - - - - - - - - + +
+
+ <%= image_tag product.image.url(:sm)%> +
+

<%= link_to product.title,admin_product_path(product) %>

+

<%= product.description %>

+

數量: <%= product.quantity %>

+
+
+
+ <% end %> -
TitleDescriptionQuantityImage]
<%= product.title %><%= product.description %><%= product.quantity %><%= product.image.url.to_s%>
\ No newline at end of file + + + diff --git a/app/views/admin/products/show.html.erb b/app/views/admin/products/show.html.erb new file mode 100644 index 0000000..e87bad8 --- /dev/null +++ b/app/views/admin/products/show.html.erb @@ -0,0 +1,15 @@ +
+
+
+<%= image_tag @product.image.url(:sm)%> +
+
+ 這是[<%= @product.title %>]
+ <%= @product.description %>
+ 數量:<%= @product.quantity %>
+
+
+ + + + diff --git a/app/views/layouts/_nav.html.erb b/app/views/layouts/_nav.html.erb index d43964a..831d6d8 100644 --- a/app/views/layouts/_nav.html.erb +++ b/app/views/layouts/_nav.html.erb @@ -1,6 +1,6 @@