Reactで Uncaught TypeError: Cannot read property 'setState' of undefined と怒られた時の対処方

コンストラクタで明示的にthisをbindして上げる必要があるらしい

constructor(props) {
  super(props);
  this.onChangeValue = this.onChangeValue.bind(this);
}

参考

ES6でReact使ってたらsetStateがundefinedとか怒られた件 - とっしぃのTech Memo

Reactで Uncaught TypeError: Cannot read property 'setState' of undefined と怒られる場合の対処法 - Qiita

Railsでall_hourメソッドが欲しい

Railsの時間関係の便利なメソッド達 all_month, all_day などなど…

でもall_hour がない

作ってしまおう

class ActiveSupport::TimeWithZone
  def all_hour
    beginning_of_hour..end_of_hour
  end
end
Time.current.all_hour 

# => Mon, 26 Jun 2017 19:00:00 JST +09:00..Mon, 26 Jun 2017 19:59:59 JST +09:00

大満足

RailsでDBに配列Arrayを保存する

RailsでDBに配列を保存する方法

serialize :column_name を指定

RailsでDBに配列を保存する方法(サンプルコード)

class Hoge < ApplicationRecord
  serialize :arr
end

hoge = Hoge.new(arr: [1, 2, 3])
puts hoge.arr # => [1, 2, 3]

Arrayと明示するとこういう使い方もできるみたい

class Hoge < ApplicationRecord
  serialize :arr, Array
end

hoge = Hoge.new
hoge.arr << 1 << 2 << 3
puts hoge.arr # => [1, 2, 3]

Railsのpartialに変数を渡す方法

<%= render partial: 'hoges/index', locals: { moge: @user.moge } %>

localsで変数を指定するだけ

部分テンプレートでmogeが使えるようになります。

renderの後のpartialも必要。忘れそう…

# hoges/index.html.erb
<%= moge %>

Railsでprimary_keyとforeign_keyの両方を指定して主キーではないカラムで関連付けする

こんな関連付けのモデルがあったとして

class Atable < ApplicationRecord
  has_one :btable
  has_one :ctable
end

class Btable < ApplicationRecord
  belongs_to :atable
end

class Ctable < ApplicationRecord
  belongs_to :atable
end

bからcを呼び出すのに

Btable.find(1).atable.ctable

としなきゃいけないのはだるい

btables.atable_id = ctables.atable_id の条件で関連付けしたい

primary_key, foreign_keyを両方指定して関連付けをする

こうなる

class Atable < ApplicationRecord
  has_one :btable
  has_one :ctable
end

class Btable < ApplicationRecord
  belongs_to :atable
  has_one :ctable, primary_key: :atable_id, foreign_key: :atable_id
end

class Ctable < ApplicationRecord
  belongs_to :atable
  belongs_to :btable, primary_key: :atable_id, foreign_key: :atable_id
end