LoginSignup
7
8

More than 5 years have passed since last update.

Railsでよく使うけど、なぜか全然覚えられないやつら

Last updated at Posted at 2016-09-09

このページを作った理由

Railsなんですけど、毎日書いていても、久々に書いていても全然覚えられないやつらがたくさんいますよね。
なので今後は調べる度に必ずここを更新して、ガンガン追加していこうと思います!!

Migration

db/migrate/00000000000000_change_db_scheme.rb

# limit, default, not_null などはモデル側で設定するのが好ましいとし、以下のみの説明とします

class ChangeDbScheme < ActiveRecord::Migration

  # 新規テーブルの作成
  create_table :table_names do |t|
    t.string  :column_name
    t.integer :***
    ...

    t.timestamps
  end

  # テーブル名変更
  rename_table  :table_names, :new_table_names

  # カラム追加
  add_column    :table_names, :new_coulmn, :string

  # カラム名変更
  rename_column :table_names, :column_name, :new_column_name

  # カラム型変更
  change_column :table_names, :column_name, :string

  # カラム削除
  remove_column :table_names, :column_name


  # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *   
  # 既存データの書き換え
  Users.all.each do |u|
    u.name = "#{u.name}様"
    u.save
  end

end

Relation

前提とするモデル User(users), Post(posts)

app/models/user.rb
class User < ActiveRecord::Base

  # 親 -> has_many, foreign_key -> 子ID
  has_many :posts, foreign_key: 'user_id', class_name: Post

end
app/models/post.rb
class Post < ActiveRecord::Base

  # 子 -> belongs_to, foreign_key -> 子ID
  belongs_to :user, foreign_key: 'user_id', class_name: User

end

インタンス変数にセット、アクセス


@u = User.finf(1)

# セット
@u.instance_variable_set(:@hoge, 'hoge')

# アクセス
@u.instance_variable_get(:@hoge)

HashのkeyにStringでもSymboleでもアクセスする

irb

# Hash.with_indifferent_access
irb(main):001:0> hash = {
irb(main):002:1*   symbol:    'symbol',
irb(main):003:1*  'string' => 'string'
irb(main):004:1> }.with_indifferent_access
# => {"symbol"=>"symbol", "string"=>"string"}

irb(main):005:0> hash[:symbol]
# => "symbol"
irb(main):006:0> hash['symbol']
# => "symbol"

irb(main):007:0> hash['string']
# => "string"
irb(main):008:0> hash[:string]
# => "string"

# 無敵になる

コンソールから色々作成

g は generate の略

# controller, viewの作成
rails g controller Users index show edit ...

# modelの作成
rails g  model User  name:string ...

# mailerの作成
rails g mailer user_mailer contact ...

日付・時間(DateTime, Time, Date)の取り扱い


# conmming soon...

7
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8