Forum: Ruby on Rails Polymorphic has_many :through, and the << method

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
A9e5ce6f28587baa2a566eb4f2d76c13?d=identicon&s=25 Jon (Guest)
on 2007-02-08 19:27
(Received via mailing list)
I'm trying to persuade polymorphic has_many :through methods to work

Some background - I have users moderating messages & photos.  So, the
models are Account, Moderation, Message, and Photo.  An account
has_many moderations, and has_many messages and photos through
moderations.  I'm just going to talk about messages here for brevity -
no photos.

class Account < ActiveRecord::Base
  has_many :moderations

  has_many :messages, :through => :moderations, :source => :message,
    :conditions => "moderations.content_type = 'Message'"

class Moderation < ActiveRecord::Base
  belongs_to :account
  belongs_to :content, :polymorphic => true

  belongs_to :message, :foreign_key => 'content_id'

class Message < ActiveRecord::Base
  has_many :moderations, :as => :content
  has_many :accounts, :through => :moderations

This is really close to working properly.  I can do @account.messages
or @message.accounts and it'll work fine.  However, trying to use one
of the habtm association methods usually fails.  For instance :

>> @account.messages << new_message
NoMethodError: undefined method `message_id=' for #<Moderation:

I've worked around it by adding a message_id= method to the Moderation
class, which simply sets content_id appropriately.  But I'm sure I'm
missing some magic option on the has_many :through relationship that
will fix this.

Any ideas?
This topic is locked and can not be replied to.