【Rails4】deviseとactive_adminで一般ユーザーと管理者ユーザーを作成
先にactive_adminで管理者ユーザー作成(deviseもインストールされる)
Rails4でActiveAdminを使ってみる - zakihayaメモ
次にdeviceで一般ユーザー作成
Rails4 にて Devise でユーザー登録・ログイン認証・認可の機能を追加 | EasyRamble
一般ユーザーのフィールド追加
rails g migration AddColumnsToUsers
class AddColumnsToUsers < ActiveRecord::Migration def change add_column :users, :name1,:string, null: false, default: "" add_column :users, :name2,:string, null: false, default: "" add_column :users, :birthday,:date add_column :users, :zip,:integer, null: false, default: 12345678 add_column :users, :pref,:string, null: false, default: "" add_column :users, :address1,:string, null: false, default: "" add_column :users, :address2,:string, null: false, default: "" add_column :users, :address3,:string add_column :users, :tel,:string end end
bundle exec rake db:migrate
一般ユーザーのフィールドにvalidation(通常のvalidationと同じ)
app/models/user.rb
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable validates :name1, presence: true validates :name2, presence: true validates :zip, presence: true validates :pref, presence: true validates :address1, presence: true validates :address2, presence: true validates :address3, presence: true end
追加したカラムをstrong_parametersに追加して、Controller経由でDBに保存できるようにする
Rails の認証プラグイン Devise での Strong Parameters について | EasyRamble
app/controllers/application_controller.rb
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 before_filter :configure_permitted_parameters, if: :devise_controller? protected def configure_permitted_parameters [:name1, :name2, :birthday, :zip, :pref, :address1, :address2, :address3, :tel].each do |param| devise_parameter_sanitizer.for(:sign_up) << param end [:name1, :name2, :birthday, :zip, :pref, :address1, :address2, :address3, :tel].each do |param| devise_parameter_sanitizer.for(:account_update) << param end end end
active_adminの画面に一般ユーザーが表示されるようにする
rails generate active_admin:resource User
管理画面から編集可能なパラメータを設定。
# app/admin/user.rb ActiveAdmin.register User do permit_params :name, :address end
一般ユーザーのviewカスタマイズ
Ruby - DeviseでViewをカスタマイズする - Qiita
・メーラー設定
⇒今度書く
・deviseの日本語化
【Rails】deviseを日本語対応した - avosalmonのブログ
【Rails】PaperClip + active_adminで画像をアップロード
PaperClipを使うためにはImageMagikが必要なので、インストールされていない場合はインストールする。
# MacのHomeBrewでインストールする場合 brew install imagemagick
Gemfile
gem 'paperclip', '~> 4.1'
Migration
rails g migration AddFileUploadToItemImages
class AddFileUploadToItemImages < ActiveRecord::Migration def change add_attachment :item_images, :image end end
Model
has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }, # 1つのモデルが複数の画像をもつ(has_many)場合、下記の指定が必要らしい :path => ":rails_root/public/system/:attachment/:id/:style/:filename", :url => "/system/:attachment/:id/:style/:filename" validates_attachment :image, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png"] }
ActiveAdmin
app/admin/item_image.rb # permit_paramsで添付ファイルのフィールド名(今回はimage)を追加 permit_params :name, :item_id, :image form do |f| f.inputs "アイテム画像" do f.input :item f.input :name f.input :image, :as => :file, :hint => f.object.new_record? ? "" : f.template.image_tag(f.object.image.url(:thumb)) end f.actions end show do |item_image| attributes_table do row :name row :item # show画面で画像を表示するためのタグを追加 row :image do image_tag(item_image.image.url(:medium)) end end end
こんな感じで画像をアップロードできるようになりました。
参考記事
Paperclip with Rails4 and active admin
RailsでPaperclipを使ってみたメモ [俺の備忘録]
Rails4+Paperclip+ActiveAdminのメモ - Qiita
【Rails】active_adminでモデルのカラム名にcountryを使うとエラー
active_adminで管理しているモデルに"country"を含むカラムがあると以下のようなエラーが出ます。
ActionView::Template::Error (To use the :country input, please install a country_select plugin, like this one: https://github.com/jamesds/country-select): 1: insert_tag renderer_for(:edit)
country_selectとかいうプラグインを使えと言われるけど、使いたくない。
下記のように、フォームでcountryカラムの型をstringで指定してやることで解決。
app/admin/item.rb form do |f| f.inputs "アイテム詳細" do f.input :name f.input :price f.input :item_category_id f.input :description f.input :material f.input :country, :as => :string end f.actions end
参考記事
ruby on rails - To use the :country input, please install a country_select plugin - Stack Overflow
【Gitメモ】マージのやり方
# masterブランチに切り替え git checkout master # masgerブランチにマージ git merge branch_name # 不要になったbranchを削除 git branch -d branch_name
【Rails】deviseを日本語対応した
config/application.rb
config.i18n.default_locale = :ja
config/locales/devise.ja.ymlを作成し、以下を記入。
# Additional translations at https://github.com/plataformatec/devise/wiki/I18n ja: devise: confirmations: confirmed: "アカウントの確認が成功しました。" send_instructions: "アカウントの確認方法をメールでご連絡します。" send_paranoid_instructions: "あなたのメールアドレスが登録済みの場合、アカウントの確認方法をメールでご連絡します。" failure: already_authenticated: "既にログイン済みです。" inactive: 'アカウントが有効になっていません。' invalid: 'メールアドレスかパスワードが違います。' locked: "アカウントがロックされています。" last_attempt: "もう一回ログインに失敗したらアカウントがロックされます。" not_found_in_database: "メールアドレスまたはパスワードが無効です。" timeout: "一定時間が経過したため、再度ログインが必要です" unauthenticated: "続けるには、ログインまたは登録(サインアップ)が必要です。" unconfirmed: "続ける前に、アカウントの確認をお願いします。" mailer: confirmation_instructions: subject: "アカウントの登録方法" reset_password_instructions: subject: "パスワードの再設定" unlock_instructions: subject: "アカウントのロック解除" omniauth_callbacks: failure: "%{kind} から承認されませんでした。理由:%{reason}" success: "%{kind} から承認されました。" passwords: no_token: "パスワードリセットのメール以外からは、このページにアクセスする事ができません。もしパスワードリセットのメールから来ている場合は、正しいURLでアクセスしていることを確認して下さい。" send_instructions: "パスワードのリセット方法をメールでご連絡します。" send_paranoid_instructions: "メールアドレスが登録済みの場合、パスワード復旧用ページヘのリンクをメールでご連絡します。" updated: "パスワードを変更しました。ログイン済みです" updated_not_active: "パスワードを変更しました。" registrations: destroyed: "アカウントを削除しました。ぜひまたのご利用をお待ちしております!" signed_up: "ようこそ!アカウント登録を受け付けました。" signed_up_but_inactive: "アカウントは登録されていますが、有効になっていないため利用できません。" signed_up_but_locked: "アカウントは登録されていますが、ロックされているため利用できません。" signed_up_but_unconfirmed: "確認メールを、登録したメールアドレス宛に送信しました。メールに記載されたリンクを開いてアカウントを有効にして下さい。" update_needs_confirmation: "アカウント情報が更新されました。新しいメールアドレスの確認が必要です。更新確認のメールを新しいメールアドレス宛に送信しましたので、メールを確認し記載されたリンクを開き、新しいメールアドレスの確認をお願いします。" updated: "アカウントが更新されました。" sessions: signed_in: "ログインしました。" signed_out: "ログアウトしました。" unlocks: send_instructions: "アカウントのロックを解除する方法をメールでご連絡します。" send_paranoid_instructions: "アカウントが存在する場合、ロックを解除する方法をメールでご連絡します。" unlocked: "アカウントのロックが解除されました。続けるにはログインして下さい。" errors: messages: already_confirmed: "は既に登録済みです。ログインしてください" confirmation_period_expired: "%{period}以内に確認する必要がありますので、新しくリクエストしてください。" expired: "有効期限切れです。新しくリクエストしてください。" not_found: "は見つかりませんでした。" not_locked: "ロックされていません。" not_saved: one: "1つのエラーにより、%{resource} を保存できませんでした:" other: "%{count} 個のエラーにより、%{resource} を保存できませんでした:"
Webサーバーを再起動し、日本語になっていることを確認。