Help understand polymorphic associations (rails)

I know that there are many resources in this, but it’s difficult for me to connect any of them with my situation, so I was hoping that someone could help me clarify how this works:

Basically, I have a model Action(which is created at any time when a user does something that affects another user, for example, by commenting on his article or by voting on someones photos), these actions will be listed in the user control panel as all actions that happened to them like a stream ... sort of like a github news feed

Github's "News Feed"

I decided to go with the creation of a polymorphic association, here is what my model looks like:

class Action < ActiveRecord::Base
  belongs_to :instigator, :polymorphic => true
  belongs_to :victim, :polymorphic => true
end

, , , , , User

class User < ActiveRecord::Base
  has_many :actions, :as => :instigator
  has_many :actions, :as => :victim
end

, , , , User.find(1).actions, , instigator, victim, , have_many , , victim.

:

create_table :actions do |t|
  t.references :instigator, :polymorphic => true
  t.references :victim, :polymorphic => true
  t.string :action_performed
  t.references :resource, :polymorphic => true
  t.timestamps
end

, SO.

+3
2

. , , .

Rails:

class User < ActiveRecord::Base
  has_many :instigator_actions, :class_name => "Action", :as => :instigator
  has_many :victim_actions, :class_name => "Action", :as => :victim
  has_many :actions, :finder_sql => '
       SELECT a.* 
       FROM   actions a
       WHERE  (a.instigator_type = "User" AND instigator_id = #{id}) OR 
              (a.victim_type     = "User" AND victim_id     = #{id})'
end

Actions , .

u1.instigator_actions.create(:victim => u2)

u1.victim_actions.create(:instigator => u2)

, , actions.

u1.actions
+2

-, Single Table Inheritance. , - . (, - , 2 , , .)

, . , . ,

class Action < ActiveRecord::Base
  belongs_to :actionable, :polymorphic => true
end

actionable . , . .

The Rails Way by Obie Fernandez , , .

+1

Source: https://habr.com/ru/post/1763385/


All Articles