「Ruby on Rails」の版間の差分

提供: sha.ngri.la
移動先: 案内検索
(app/models/user.rb)
(app/models/user.rb)
276行目: 276行目:
 
このメールはパスワード忘れた時の再登録用です。
 
このメールはパスワード忘れた時の再登録用です。
  
おそらく、WEBrick Server使っているでしょうから、<code>[http://localhost:3000/users/password/edit?reset_password_token=upy7V8UMLuMbjBR9jiee ]</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を使えるようにするまでのとおり。いまのところ、不具合なく動いています。

インストール

Ruby on RailsをVPSで動かす

アップグレード

$ 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 アプリケーションを作る

  1. アプリケーションを作る
    $ rails new [アプリケーション名] -d mysql
    
  2. scaffoldを生成
    $ rails g scaffold [モデル名単数形] [カラム名1]:[メソッド名1] [カラム名2]:[メソッド名2] .....
    

    $ rails g scaffold interested id:integer url:string title:string tag:string lastmodified:datetime
    
  3. config/database.ymlを編集
  4. migrateを実行
    $ rake db:create
    $ rake db:migrate
    
  5. 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
    

    と変更する。

  6. Railsコマンドでgenerateしたのを取り消す。上記でgenerateした場合は、
    $ rails destroy scaffold interested
    
  7. 有効なルートを表示する
    $ rake routes
    

1対1の参照

Modelファイルの編集

例えば、interestedという名のモデルからbookmarkという名のモデルを参照する場合。

  1. app/models/interested.rb
class Interested < ActiveRecord::Base
  belongs_to :bookmark
end
  1. app/models/bookmark.rb
class Bookmark < ActiveRecord::Base
  has_one :interested
end

Controlファイルの編集

  1. app/controllers/interested.rb
def index
  @interesteds = Interested.order("id DESC").limit(10)
  @bookmarks = Bookmark
end

Viewファイルの例

  1. 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"})

カラムを追加する

  1. クラス名は AddFooToBarsとします。Fooは追加するカラム名Barsはテーブル名です。ここのFooはカラム名と違っても構いません。
  2. カラム名:データ型 の部分、カラム名は追加するカラム名、データ型はinteger,stringなどです。
    rails g migration クラス名 カラム名:データ型( カラム名:データ型)
    rails g migration AddFooToBars foo:integer
    rake db:migrate
  3. カラムを削除する場合には次のようにします。
    rails g migration RemoveFooFromBars

Link

Twitter Bootstrapを使う

  1. Gemfileに追加
    gem "twitter-bootstrap-rails", :group => :assets
  2. Terminal
  3. $ 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
    
  4. 後始末 ナビバーがページと重なっているときは、 bootstrap_and_overrides.css.lessにpadding-top:60px;を追加して記載。
    body { padding-top:60px; }
    

Bootstrap3

Link

will_paginateを使う

will_paginateをインストールしてから、bootstrap-will_paginateをインストールします。

<%= will_paginate @collection, renderer: BootstrapPagination::Rails %>と書くようにありますが、<%= will_paginate @collection %>のみで動作しました。

kaminariを使う

paginationを使えるようになります。

  1. /Gemfile に
    gem 'kaminari'
    

    を追加して、bundle install。

    $ bundle install
    
  2. /app/controllers/interesteds_controller.rb に
    def index
      @interesteds = Interested.order("id DESC").page(params[:page]).per(10)
    end
    
  3. /app/views/interesteds/index.html.erb に
    <%= paginate @interesteds %>
    

    を追加

Twitterbootstrapを使うときは、Twitterbootstrapを適用してからkaminariを使う。

表示を整える

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

act as tagable on

Link