「Ruby on Rails」の版間の差分
細 (→app/models/user.rb) |
細 (→app/models/user.rb) |
||
276行目: | 276行目: | ||
このメールはパスワード忘れた時の再登録用です。 | このメールはパスワード忘れた時の再登録用です。 | ||
− | おそらく、WEBrick Server使っているでしょうから、<code> | + | おそらく、WEBrick Server使っているでしょうから、<code>http://localhost:3000/users/password/edit?reset_password_token=upy7V8UMLuMbjBR9jiee</code>にアクセスすれば、認証されます。 |
<pre> | <pre> | ||
Sent mail to | Sent mail to |
2014年4月4日 (金) 17:42時点における版
使えるようにするまでは、Mountain LionでRuby On Railsを使えるようにするまでのとおり。いまのところ、不具合なく動いています。
目次
- 1 インストール
- 2 アップグレード
- 3 Rails アプリケーションを作る
- 4 1対1の参照
- 5 リンクを作成する
- 6 カラムを追加する
- 7 Twitter Bootstrapを使う
- 8 will_paginateを使う
- 9 kaminariを使う
- 10 表示を整える
- 11 deviseを使ってユーザ認証機能をつける
- 11.1 Gemfileを編集
- 11.2 bundle install
- 11.3 rails g devise:install
- 11.4 rails g devise user
- 11.5 app/models/user.rb
- 11.6 db/migrate/**************_devise_create_users.rb
- 11.7 rake db:migrate
- 11.8 app/controllers/****.controller.rb(****は、認証したいコントローラー)に berfore_filter :authenticate_user! を追加する。
- 11.9 config/routes.rb
- 11.10 ログイン中だけ表示させたい項目、例えば new のボタンなら、app/views/モデル名/inde.html.erb 等の次の部分を編集
- 11.11 deviseの各機能へのリンク
- 11.12 Link
- 12 act as tagable on
- 13 Link
インストール
アップグレード
$ cd ~/.rbenv $ git pull origin master $ cd ~/.rbenv/plugins/ruby-build $ git pull origin master $ rbenv install -l $ rbenv install 2.1.1 $ rbenv versions $ rbenv shell バージョン $ gem install rails
Rails アプリケーションを作る
- アプリケーションを作る
$ rails new [アプリケーション名] -d mysql
- scaffoldを生成
$ rails g scaffold [モデル名単数形] [カラム名1]:[メソッド名1] [カラム名2]:[メソッド名2] .....
例
$ rails g scaffold interested id:integer url:string title:string tag:string lastmodified:datetime
- config/database.ymlを編集
- migrateを実行
$ rake db:create $ rake db:migrate
- config/routes.rbを編集。上記のrails g scaffoldの例なら、
InterestedIn::Application.routes.draw do resources :interesteds end
を
InterestedIn::Application.routes.draw do resources :interesteds root :to =>"interesteds#index" end
と変更する。
- Railsコマンドでgenerateしたのを取り消す。上記でgenerateした場合は、
$ rails destroy scaffold interested
- 有効なルートを表示する
$ rake routes
1対1の参照
Modelファイルの編集
例えば、interestedという名のモデルからbookmarkという名のモデルを参照する場合。
- app/models/interested.rb
class Interested < ActiveRecord::Base belongs_to :bookmark end
- app/models/bookmark.rb
class Bookmark < ActiveRecord::Base has_one :interested end
Controlファイルの編集
- app/controllers/interested.rb
def index @interesteds = Interested.order("id DESC").limit(10) @bookmarks = Bookmark end
Viewファイルの例
- app/views/interesteds/index.html.erb
<%= link_to interested.bookmark.title, bookmark_path(interested.bookmark_id) %>
bookmarkモデル内にtitleがあるなら、interested.bookmark.title
で、参照する。
参照先のbookmarkへのパスは、bookmark_path(interested.bookmark_id)
リンクを作成する
link_to("表示する文字",url)
例えば、モデル名がinterestedでデータベースのカラム名がtitle、urlの場合(この認識で正しいのか?)、
link_to( interested.title ,interested.url)
3番目の引数で<a>タグの属性も指定できる。
link_to( interested.title ,interested.url,{:target=>"_blank"})
カラムを追加する
- クラス名は AddFooToBarsとします。Fooは追加するカラム名Barsはテーブル名です。ここのFooはカラム名と違っても構いません。
- カラム名:データ型 の部分、カラム名は追加するカラム名、データ型はinteger,stringなどです。
rails g migration クラス名 カラム名:データ型( カラム名:データ型)
rails g migration AddFooToBars foo:integer
rake db:migrate
- カラムを削除する場合には次のようにします。
rails g migration RemoveFooFromBars
Link
Twitter Bootstrapを使う
- Gemfileに追加
gem "twitter-bootstrap-rails", :group => :assets
- Terminal
- 後始末
ナビバーがページと重なっているときは、
bootstrap_and_overrides.css.lessにpadding-top:60px;を追加して記載。
body { padding-top:60px; }
$ bundle install (略) $ rails g bootstrap:install (略) $ rails g bootstrap:layout [LAYOUT_NAME] [*fixed or fluid]
例 fixedは1行、fluidは2行のことだと思う、、、
$ rails g bootstrap:layout application fixed
$ rails g bootstrap:themed [RESOURCE_NAME]
例
$ rails g bootstrap:themed interesteds
Bootstrap3
- benjamincanac/bootstrap3-rails · GitHub
- decioferreira/bootstrap-generators · GitHub
- bootstrap3-rails | RubyGems.org | your community gem host
Link
- Twitter Bootstrap
- seyhunak/twitter-bootstrap-rails · GitHub
- Twitter bootstrap on rails
- 続『5分でRails3アプリ』をやってみた - 『Twitter Bootstrap』で見た目をサクッと変えてみた - 牌語備忘録 - pygo
- #328 Twitter Bootstrap Basics - RailsCasts
- thomaspark/bootswatch · GitHub
will_paginateを使う
will_paginateをインストールしてから、bootstrap-will_paginateをインストールします。
<%= will_paginate @collection, renderer: BootstrapPagination::Rails %>
と書くようにありますが、<%= will_paginate @collection %>
のみで動作しました。
- mislav/will_paginate · GitHub
- yrgoldteeth/bootstrap-will_paginate · GitHub
- Home · mislav/will_paginate Wiki · GitHub
kaminariを使う
paginationを使えるようになります。
- /Gemfile に
gem 'kaminari'
を追加して、bundle install。
$ bundle install
- /app/controllers/interesteds_controller.rb に
def index @interesteds = Interested.order("id DESC").page(params[:page]).per(10) end
- /app/views/interesteds/index.html.erb に
<%= paginate @interesteds %>
を追加
Twitterbootstrapを使うときは、Twitterbootstrapを適用してからkaminariを使う。
- #254 Pagination with Kaminari - RailsCasts
- kaminari + bootstrap によるデザイン崩れに対応する - akiinyoオフィシャルWeb日記
- gabetax/twitter-bootstrap-kaminari-views · GitHub
表示を整える
- 属性セレクタで、スタイルシートを柔軟に! [ホームページ作成 All About]
deviseを使ってユーザ認証機能をつける
Gemfileを編集
gem "devise"
bundle install
$ bundle install
rails g devise:install
$ rails g devise:install (略) =============================================================================== Some setup you must do manually if you haven't yet: 1. Ensure you have defined default url options in your environments files. Here is an example of default_url_options appropriate for a development environment in config/environments/development.rb: config.action_mailer.default_url_options = { :host => 'localhost:3000' } In production, :host should be set to the actual host of your application. 2. Ensure you have defined root_url to *something* in your config/routes.rb. For example: root :to => "home#index" 3. Ensure you have flash messages in app/views/layouts/application.html.erb. For example: <p class="notice"><%= notice %></p> <p class="alert"><%= alert %></p> 4. If you are deploying Rails 3.1+ on Heroku, you may want to set: config.assets.initialize_on_precompile = false On config/application.rb forcing your application to not access the DB or load models when precompiling your assets. 5. You can copy Devise views (for customization) to your app by running: rails g devise:views ===============================================================================
rails g devise user
$ rails g devise user $ rails g devise:views
app/models/user.rb
ユーザー登録の際に入力したメールアドレスにメールを送って確認するために、:confirmable を deviseの行に追加する。
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable # :registerable, devise :database_authenticatable, :confirmable, :recoverable, :rememberable, :trackable, :validatable # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me # attr_accessible :title, :body has_many :bukumas, :dependent => :destroy end
テスト環境でメールの送信できない場合は、ログに表示されたurlを直接開けば認証できます。
このメールはパスワード忘れた時の再登録用です。
おそらく、WEBrick Server使っているでしょうから、http://localhost:3000/users/password/edit?reset_password_token=upy7V8UMLuMbjBR9jiee
にアクセスすれば、認証されます。
Sent mail to Date: From: please-change-me-at-config-initializers-devise@******.com Reply-To: please-change-me-at-config-initializers-devise@*****.com To: Message-ID: <533eeb192f62c_171f3fc772561f9892665@yaal.private.mail> Subject: Reset password instructions Mime-Version: 1.0 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: 7bit <p>Hello </p> <p>Someone has requested a link to change your password. You can do this through the link below.</p> <p><a href="http://localhost/users/password/edit?reset_password_token=upy7V8UMLuMbjBR9jiee">Change my password</a></p> <p>If you didn't request this, please ignore this email.</p> <p>Your password won't change until you access the link above and create a new one.</p>
db/migrate/**************_devise_create_users.rb
次の部分のコメントをはずす
## Confirmable t.string :confirmation_token t.datetime :confirmed_at t.datetime :confirmation_sent_at t.string :unconfirmed_email # Only if using reconfirmable
rake db:migrate
$ rake db:migrate
この辺りでサーバをリスタート(ctrl-c,rails s)しないと、アクセスしてもエラーになる。
app/controllers/****.controller.rb(****は、認証したいコントローラー)に berfore_filter :authenticate_user! を追加する。
class ****Controller < ApplicationController before_filter :authenticate_user!, :except => [:index, :show]
config/routes.rb
match ':controller(/:action(/:id))(.:format)'
の部分のコメントをはずす。
ログイン中だけ表示させたい項目、例えば new のボタンなら、app/views/モデル名/inde.html.erb 等の次の部分を編集
<% if user_signed_in? -%> <%= link_to t('.new', :default => t("helpers.links.new")), new_article_path, :class => 'btn btn-primary' %> <% end %>
deviseの各機能へのリンク
ログインのリンク
<%= link_to "login", user_session_path %>
ユーザー情報の編集ページへのリンク
ログイン中のユーザーのメールアドレスを表示するのは、link_to_current_user
<%= link_to current_user.email, edit_user_registration_path %>
ログアウトするためのリンク
<%= link_to "logout", destroy_user_session_path, method: :delete %>
Link
- deviseを用いたメールによるactivation方法 · moriC/study_rails Wiki · GitHub
- Deep valley まとめ版 - RailsでDeviseを使ってみた
- RailsApps/rails3-bootstrap-devise-cancan · GitHub
- Railsの第4世代認証エンジンDeviseのREADMEを翻訳してみた - LazyLoadLife
- Rails3アプリにDeviseで簡単に認証システムを組み込む - hrendohの日記
- Ruby on Rails ユーザー認証エンジン「Devise」の参考記事まとめ | CodeNote.net