【Rails4】ActionMailerを使う(heroku からメールを送信する)
環境
Rails4.1.8
heroku SendGrid
目的
- productionモード(heroku)でメールが送れるようにする
1. herokuにアドオン SendGridをインストール
# heroku login # heroku addons:add sendgrid:starter
2. herokuから設定を取得
# heroku config:get SENDGRID_USERNAME # => xxxx@heroku.com # heroku config:get SENDGRID_PASSWORD # => password
3. herokuにherokuから設定を取得
# config/environment.rb ActionMailer::Base.smtp_settings = { :address => 'smtp.sendgrid.net', :port => '587', :authentication => :plain, :user_name => 'xxxx@heroku.com', :password => 'password', :domain => 'heroku.com', :enable_starttls_auto => true }
4. ローカルでテスト
# MailerとしてNotiferクラスにtest_mailを作成 # rails g mailer notifier でMailerを追加できる Notifier.test_mail.deliver
【Rails4】I18nでエスケープさせない + DBのないモデルの日本語化
目的
1. 改行を含む文章をI18nで定義する
2. DBのないモデルのattributsを日本語化する
1. xxx_html で定義するとエスケープされない
# config/locales/ja.yml body_html:| 1行目<br /> 2行目 # View <%= t('body_html') %> # => # 1行目<br /> # 2行目
2. activerecordでなくてactivemodelで定義
# config/locales/ja.yml ja: activemodel: models: attributes: test: name: 名前 # Model class Test include ActiveModel::Model attr_accessor :name end # Controller def test @test = Test.new() end # View <%= form_for @test do |f| %> <%= f.file_field(:name) %> <% end %>
【Rails4】【Ajax】非同期でファイルをアップロードする
目的
Railsのフォームヘルパーを使い、Ajaxでファイルをアップロードしたい。
form_forでremote:trueしただけではActionController::InvalidAuthenticityTokenというエラーになる。
1. gem のインストール
下記を追記して、bundle installする
# Gemfile gen 'remotipart'
2. jQueryの設定で下記を追記
# assets/javascript/application.js //= require jquery.remotipart
3. フォームの作成
# View <%= form_for @upload, :html => {multipart: true, remote: true, authenticity_token: true} do |f| %> <%= f.file_field :file %> <% end %>
参考
【Rails4】【bootstrap3】アイコンフォントを表示する
目的
gem でbootstrap3をインストールして、bootstrap3アイコンフォントが表示されること
1. fontsファイルをコピーする
bundle install したtwitter-bootstrap-railsのフォルダからfontsファイルをコピーして任意のファルダにペーストする
(今回はapp/assets/fontsフォルダを作成して使用)
2. config/application.rb に以下を追記
assetsパイプラインで読み込むファイルを追加する
config.assets.paths << "#{Rails}/app/assets/fonts" # パスは1でペーストしたフォルダ
3. app/assets/stylesheets/application.css に以下を追記
assetsパイプライン用にパスを上書く
@font-face { font-family: 'Glyphicons Halflings'; src: url('../assets/glyphicons-halflings-regular.eot'); src: url('../assets/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../assets/glyphicons-halflings-regular.woff') format('woff'), url('../assets/glyphicons-halflings-regular.ttf') format('truetype'), url('../assets/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg'); }
【Rails4】【bootstrap3】郵便番号から住所検索する。
環境
Rails 4.1.8
Bootstrap3
ソースコード
郵便番号検索には「AjaxZip3」というライブラリを使用した。
AjaxZip3の使い方 | Webサイト制作支援 | ShanaBrian Website
HTML(一部抜粋)
<script src="https://ajaxzip3.googlecode.com/svn/trunk/ajaxzip3/ajaxzip3-https.js" charset="UTF-8"></script> <div class="form-group"> <%= f.label :zipcode, "郵便番号/住所", :class => 'control-label col-md-2' %> <div class="controls col-md-3"> <div class="input-group"> <span class="input-group-addon">〒</span> <%= f.text_field :zipcode, :class => 'form-control', id:'zipcode_field' %> <span class="input-group-btn"> <button id="search_from_zipcode" class="btn btn-default" type="button" onclick="AjaxZip3.zip2addr('order[zipcode]','','order[address]','order[address]');", data-original-title="<%= t('messages.search_address') %>"> <span class="glyphicon glyphicon-search"></span> </button> </span> </div> </div> <div class="controls col-md-6"> <%= f.text_field :address, :class => 'form-control' %> </div> </div>
$ -> $('#zipcode_field').on("focus", (event) -> $('#search_from_zipcode').tooltip('show', { animation : false, placement : 'top', trigger : 'manual' }); );
AjaxZip3.zip2addr について
引数は次の通り。セレクタはすべてname属性で。
(郵便番号(全てまたは上3桁),郵便番号(下4桁),都道府県,市区町村,丁目番地,町域大字)
AjaxZip3の使い方 | Webサイト制作支援 | ShanaBrian Website
ツールチップについて
bootstrapのtooltipを使用。
ツールチップのトリガーとなる要素とツールチップを出したい要素が異なったので、イベントをキャッチしてmanualでtooltipを'show'している。
また、tooltipのオプションは要素内のdata属性でも指定できる。
上記のコードでは'data-original-title'でメッセージを個別に定義している。
Twitter Bootstrap使い方-javascript-v2.0.4
Rails3.2でネストしたモデルのバリデーションエラーの日本語化
なかなか苦戦したので備忘録として、バリデーションのかけ方とメッセージの日本語の2本立て
Rails3.2
ネストしたモデルのバリデーション
例)お客(Customer)に注文(Order)が1対多で紐づく場合、
お客を登録した時に一緒に注文も複数個登録したい
- Model
# customer.rb has_many :orders #「:モデル名_attributes」 attr_accessible :name, :tel, :orders_attributes # 以下でネストするモデルを指定。has_manyだから複数形。 accepts_nested_attributes_for :orders validates :name, :presence => true validates :tel, :presence => true # order.rb belongs_to :customer attr_accessible :name validates :name, :presence => true
- Controller
# order_controller.rb def create @customer = Customer.new(name:params[:name], tel:params[:tel]) params[:orders].each do |order| @customer.orders.build(name:order[:name]) # または以下でも同意 # @customer.orders << Order.new(name:order[:name]) end @customer.save! end
ネストしたバリデーションエラーメッセージの日本語化
下記のサイトどおりではうまくいきませんでした。Railsのバージョンが違うから?
http://ukstudio.jp/posts/2009/04/14/accepts_nested_attributes_for/
で、調べつつそれっぽい書き方を試すものの、別のサイトの方法でようやく解決
Rails 3.2でネストしたモデルの属性名をI18nで翻訳する。 - Sooey
# config/locales/ja.yml # order単体で登録する場合もあるため、ネストしない場合も別途記載 activerecord: models: order: 'ご注文' customer: 'お客様' attributes: order: # orderモデル name: "商品名" customer: # customerモデル name: "お名前" tel: "電話番号" customer/orders: # ネストした場合はスラッシュ区切り。インデントは他のモデルと同じ(単数・複数形に注意) name: "商品名"
久しぶりにherokuにpushしたら出たエラーとその対処法
datepickerを追加して出たエラー
- エラー
couldn't find file 'jquery-ui'
- 対処法
# assets/javascripts/application.js //= require jquery //= require jquery-ui
↓
# assets/javascripts/application.js //= require jquery //= require jquery.ui.all
◆参考
javascript - Couldn't find file 'jquery-ui' - Stack Overflow
GitHub - jquery-ui-rails/jquery-ui-rails: jQuery UI for the Rails asset pipeline
assets:precompileでエラー
- エラー
could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432?
- 対処法
# config/application.rb に以下を追加 # For Heroku config.assets.initialize_on_precompile = false
◆参考
[Heroku] Rails 3.2 アプリを git push すると rake assets:precompile でエラーが出るときの対処法 | CodeNote