Reputation: 437
I've been stuck on this problem for a couple of days now, I found some other stack questions that we're similar but there solutions didn't help. I'm trying to create two seperate polymorphic associations between two tables. I have a users table, a business table and a messages table. I wan't the user to be able to message each other with a one on one conversation.
This is my messages schema:
class CreateMessages < ActiveRecord::Migration
def change
create_table :messages do |t|
t.references :receiver, polymorphic: true, index: true
t.text :message
t.boolean :status, default: false
t.references :sender, polymorphic: true, index: true
t.timestamps
end
end
end
Messages Model
class Message < ActiveRecord::Base
belongs_to :sender, polymorphic: true
belongs_to :receiver, polymorphic: true
scope :unread, lambda {|| where("status = false")}
end
Users Model
has_many :messages, as: :sender
has_many :messages_out, as: :receiver, source: :messages
Business Model
has_many :messages, as: :sender
has_many :messages_out, as: :receiver, source: :messages
Rails Console
2.2.1 :060 > User.first.messages_out
User Load (1.3ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
NameError: uninitialized constant User::MessagesOut
When I try to access messages as sender it works completely fine and I get the expected output. I tried changing the name of the first relationship to something else but then both of the relationships would fail.
User.first.messages
I tried several variations of this and none of them seem to be working, if setting up my database or model like this is just ill advised, and this setup can't work please let me know and any other setup would be appreciated.
Upvotes: 0
Views: 213
Reputation: 2090
You need to explicitly say which class the messages_out
method should be loading:
has_many :messages_out, as: :receiver, source: :messages, class_name: "Message"
Upvotes: 1