I'm trying to persuade polymorphic has_many :through methods to work properly.
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'" end
class Moderation < ActiveRecord::Base belongs_to :account belongs_to :content, :polymorphic => true
belongs_to :message, :foreign_key => 'content_id' end
class Message < ActiveRecord::Base has_many :moderations, :as => :content has_many :accounts, :through => :moderations end
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: 0x22ed8c8>
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? Cheers, Jon