2012/04/12

DBから取ってきた ARオブジェクトを 必要な数だけ切り出す

  • 環境:Rails3
いわゆる、あれです
PHPで言うarray_sliceですよ

    users= User.find(:all, :conditions=>[" ~省略
    
    #全体の件数
    puts('count [' + users.size.to_s + ']')
    #先頭から 3つ切り出す
    puts(users.slice(0..2).to_yaml)




2012/04/10

I18nで国際化対応 − 翻訳メッセージに 変数を使う

  • 環境:Rails3
I18n.backend.store_translations :en, :thanks => 'Thanks %{name}!'
I18n.translate :thanks, :name => 'Jeremy'
# => 'Thanks Jeremy!'

変数を入れたい部分に %{変数名}を入れる

公式ガイド:


国際化 参考ページ↓
※変数を使用する部分が{{変数名}}で間違っているけど、その他の部分は概ね参考になる 公式ガイド(英語)と見比べるのがよろしい


こちらは基本的なところがわかりやすくまとまっております↓


コードの中に日本語を書くとエラーになるときの おまじない


  • 環境:Rails3

コードの中に日本語・・・
まあたとえば、

a = 'こんにちは'

↑的な?(試してないけど)

とにかく エラーが出ないためのおまじない



# encoding: utf-8

もしくは

# -*- coding: utf-8 -*-




を、ファイル頭に書く


参考)
Rails3 事始め: [Rails3] コードに日本語を書くとエラーになる件 - http://rails3try.blogspot.jp/2011/12/rails3_26.html


2012/04/07

削除されたものも検索したい時 「unscoped」を使う

論理削除とか使ってたりするときね

class Diary < ActiveRecord::Base
  # 論理削除
  default_scope where(:deleted_at => nil)


削除されたものも検索したい時 「unscoped」を使う
  # いつもの検索 deleted_at is null がSQLに付く
  Diary.find(:all, :conditions=>["id=?", id], :order=>"updated_at DESC")
  # 削除あり検索
  Diary.unscoped.find(:all, :conditions=>["id=?", id], :order=>"updated_at DESC")

ActiveRecordオブジェクトを そのままハッシュに入れたい時

 ActiveRecord(AR)オブジェクトは
各オブジェクトごとの値を attributes っていうHashで保持しているらしい

  user = User.find_by_user_id(params[:user_id])
  logger.debug(user.to_yaml)#←中身デバッグ

・DEBUGは↓こんな感じ
[DEBUG] --- !ruby/object:User
attributes:
  id: '1'
  name: username
  deleted_at: !!null 
  created_at: '2012-04-07 03:32:09'
  updated_at: '2012-04-07 13:41:55'
changed_attributes: {}
previously_changed: {}
attributes_cache: {}
marked_for_destruction: false
destroyed: false
readonly: false
new_record: false


attributesは
1件しかないARオブジェクトだったら
→ user.attributes

複数取れるARオブジェクトだったら
(プライマリキーで取得できる件数が必ず1件だったとしても find(:all 〜 とかで取得するとこっちになると思われ)
→ user[0..N].attributes