Forum: Ruby on Rails polymorphic association with single model as target

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Stefan S. (Guest)
on 2006-04-17 09:13
Hi,

I'm new to rails/ruby and not a sw programmer in the first place.

I'd like to use polymorphic associations to create tags/marks into
several dictionary tables (i.e japanese to english and japanese to
french) that share the same model. In that model I introduced a :target
field to select the database in a find query, i.e:

  def self.find(*args)
    for i in args
      if i.class == Hash then
        #i.each { |key, value| logger.info "#{key} is #{value}"}
        target = i.delete :target
      end
    end
    ... process table name base on target and call set_table_name
    super
  end

The model that contain the marks to the dictionary entries is defined
like this:
  belongs_to :ref, :polymorphic => true

I use the ref_id as foreign key (as in all the examples) and ref_type as
INTEGER with a number defining the dictionary I'd like to refer too.

Doing the "joins" myself as in the exemple below works well.

    @marks_en = DbDict.find(:all,
               :target => DBDICT_EN_TYPE,
               :joins => "as db inner join marks as ma on ma.ref_id =
db.id",
               :conditions => "ma.ref_type = " + DBDICT_EN_TYPE.to_s)

Doing a call to something like:

    @mark = Mark.find(params[:id]).ref

Does not work.  I clearly understand that this will not work out of the
box, what I would like to know is how and where do I have to override
the "ref" method to get this to work ?
Is that possible at all or am I trying to force something that's not
intended to be done this way ?


Any ideas highly appreciated!

Thanks
 StefanS
This topic is locked and can not be replied to.