3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

rails5でactive_hashのモデルをbelongs_toで参照できるようにする

Posted at

動作確認バージョン

Gemfile.lock
rails (5.0.0.1)
active_hash (1.4.1)

親モデル

# == Schema Information
#
# Table name: parents
#
#  blood_type_id :integer
#
ApplicationRecord.extend ActiveHash::Associations::ActiveRecordExtensions

class Parent < ApplicationRecord
  belongs_to_active_hash :blood_type
end

active_hashモデル

class BloodType < ActiveHash::Base
  include ActiveHash::Associations
  has_one :parent

  fields :label, :name
  add id: 1, label: 'A型',   name: 'a'
  add id: 2, label: 'B型',   name: 'b'
  add id: 3, label: 'O型',   name: 'o'
  add id: 4, label: 'AB型',  name: 'ab'
end

使用例

irb(main):001:0> parent = Parent.new(blood_type_id: 4)
=> #<Parent id: nil, blood_type_id: 4,created_at: nil, updated_at: nil>

irb(main):002:0> parent.blood_type.label
=> "AB型"
3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?