I tried to implement polymorphic related in Nogizaka.

About polymorphic related

It's kind of hard to get along with, so after a while of studying, it becomes polymorphic ...?, So I enjoyed implementing it. It feels like a memorandum, so please take a look.

Normal association

Implementing which Sakamichi Group is singing which song without defining polymorphic relations ...

nogizaka.rb


class Nogizaka < ApplicationRecord
  has_many :songs
end

keyakizaka.rb


class Keyakizaka < ApplicationRecord
  has_many :songs
end

hinatazaka.rb


class Hinatakizaka < ApplicationRecord
  has_many :songs
end

song.rb


class Song < ApplicationRecord
  belongs_to :nogizaka
  belongs_to :keyakizaka
  belongs_to :hinatazaka
end

problem

――If you want to get information about idols who sing a certain song, you have to check which idol is singing. (If you're a fan of slopes, you'll understand without checking ... lol)

python


@song = Song.take #Get an instance appropriately
@song.nogizaka #In the case of Nogizaka46 songs
@song.hinatazaka #In the case of Hinatazaka46 songs

--46 When the number of groups increases, it is necessary to add a column to the song model.

Implemented in polymorphic

--Just set polymorphic: true to references

20200620xxxx_create_songs.rb


class CreateSongs < ActiveRecord::Migration[5.2]
  def change
    create_table :songs do |t|
      t.string :name
      t.references :songable, polymorphic: true, index: true #Here! !!
      t.timestamps
    end
  end
end

schema.rb


create_table "songs", force: :cascade do |t|
    t.string "name"
    t.string "postable_type" #The type distinguishes between Nogizaka class and Keyakizaka class.
    t.integer "postable_id"
    ...(The following is omitted)
  end

I will rewrite the models as well. It's surprisingly easy.

class Nogizaka < ApplicationRecord
  has_many :songs, as: :songable
end

class Keyakizaka < ApplicationRecord
  has_many :songs, as: :songable
end

class Hinatakizaka < ApplicationRecord
  has_many :songs, as: :songable
end

class Song < ApplicationRecord
  belongs_to :songable, polymorphic: true
  # Before ↓↓↓
  # belongs_to :nogizaka
  # belongs_to :keyakizaka
  # belongs_to :hinatazaka 
  #3 lines are now 1 line!
end

So what happens ???

# @When song is Nogizaka's song
#Normal association
@song.nogizaka # =>name:"Nogizaka46", year_of_formation:2011,...
#Polymorphic related
@song.songable # =>name:"Nogizaka46", year_of_formation:2011,...

--In the above, you can get an instance of the same Nogizaka model. ――I would be happy if you could get an image of it somehow.

You can also write like this

Define a method with the same name in each model and change the behavior in it.

class Nogizaka < ApplicationRecord
  has_many :songs, as: :songable

  def cute_member
   "name:#{name},Pets:#{pet_name}"
  end
end


class Keyakizaka < ApplicationRecord
  has_many :songs, as: :songable
  
  def cute_member
   "name:#{name},Birthplace:#{birthplace}"
  end
end


class Hinatakizaka < ApplicationRecord
  has_many :songs, as: :songable

  def cute_member
   "name:#{name},catch copy:#{catch_copy}"
  end
end

result

python


#@When the song is Nogizaka
@song.songable.cute_member 
=> "name:Yoda Yuki,Pets:Gonzo"

#@When the song is Keyakizaka
@song.songable.cute_member 
=> "name:Hikaru Morita,Birthplace:Fukuoka Prefecture"

#@When the song is Hinatazaka
@song.songable.cute_member 
=> "name:Hinano Kamimura,catch copy:Hinano!"

Summary

--You can get an instance of Nogizaka model (Keyakizaka, Hinatazaka) with @ song.songable. (It's hard to get an image, and I think it's around here that makes polymorphic difficult.) ――Idols are cute after all. .. ..

Recommended Posts

I tried to implement polymorphic related in Nogizaka.
I tried to implement Firebase push notification in Java
I tried to implement the Euclidean algorithm in Java
I tried to implement a buggy web application in Kotlin
I tried to implement the Iterator pattern
I tried to implement Ajax processing of like function in Rails
I tried to organize the session in Rails
I tried to output multiplication table in Java
I tried to develop an application in 2 languages
I tried to create Alexa skill in Java
I tried to implement a server using Netty
I tried to implement file upload with Spring MVC
I tried to implement TCP / IP + BIO with JAVA
# 2 [Note] I tried to calculate multiplication tables in Java.
I tried to create a Clova skill in Java
I tried to make a login function in Java
I tried to implement Stalin sort with Java Collector
[Java] I tried to implement Yahoo API product search
~ I tried to learn functional programming in Java now ~
I tried to find out what changed in Java 9
I tried to verify yum-cron
I tried metaprogramming in Java
I tried to make an application in 3 months from inexperienced
I tried to implement the like function by asynchronous communication
I tried to collect and solve Ruby's "class" related problems.
[Rails] I tried to implement batch processing with Rake task
I tried to convert a string to a LocalDate type in Java
I tried using Dapr in Java to facilitate microservice development
I tried to make a client of RESAS-API in Java
I tried to summarize object orientation in my own way.
I tried to chew C # (indexer)
Try to implement Yubaba in Ruby
I tried to summarize iOS 14 support
I tried to interact with Java
I tried to explain the method
I tried putting Domino11 in CentOS7
I tried using JWT in Java
I tried to summarize Java learning (1)
Try to implement Yubaba in Java
I tried to summarize Java 8 now
I tried to chew C # (polymorphism: polymorphism)
I tried to explain Active Hash
I tried to create a simple map app in Android Studio
I tried to illuminate the Christmas tree in a life game
I tried to sort the data in descending order, ascending order / Rails
I tried to write code like a type declaration in Ruby
I tried to implement the image preview function with Rails / jQuery
I tried setting Java beginners to use shortcut keys in eclipse
I tried to implement flexible OR mapping with MyBatis Dynamic SQL
I tried to make Numeron which is not good in Ruby
I tried using Elasticsearch API in Java
How to implement search functionality in Rails
How to implement date calculation in Java
How to implement Kalman filter in Java
I tried to summarize the methods used
I tried migrating Processing to VS Code
Settings related to connection pool in Tomcat.jdbc
Try to implement n-ary addition in Java
I tried to summarize Java lambda expressions
[Rails] I tried to implement a transaction that combines multiple DB processes
I tried to get started with WebAssembly