Polymorphic has_many :through, and the << method

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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs