Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ruby on rails - Polymorphic Assocations using Integer ID type fields

I have a table Foo that has a polymorphic belongs_to association called bar. The foos table has the standard bar_id column. However, instead of a string-based bar_type column, I have an integer bar_type_id column. This column references the id column in the table bar_types. bar_types.name holds the name of the class that represents the class of the particular bar instance.

Does Rails (ideally >=2.3.10) allow for this type of polymorphic association?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

We did it by overriding the association_class method in a new module and included it using the :extend option. Also created a integer to string mapping hash to make things easier.

In config/initializers directory or anywhere you like, create a file and define the hash INT_OBJECT_TYPE_TO_CLASSNAME = { 0 => "Project", 1 => "Task", 2 => "Timesheet" }

class CommentObjectType < ActiveRecord::Base
  module ClassNamesAsInt
    def association_class
      return INT_OBJECT_TYPE_TO_CLASSNAME[restricted_object_type].constantize
    end
  end
end

In comments.rb

belongs_to :commentable, :polymorphic => true, :extend => CommentObjectType::ClassNamesAsInt

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...