简体   繁体   中英

Rails messaging

I m create a messaging between users. Take info from here .

But then I go for new message, I have a error.

NoMethodError in MessagesController#new
undefined method `relation_delegate_class' for "Message":String

  def new
    @message = current_user.sent_messages.new
  end

How can I fix it? Thanks.

Message model:

class Message < ActiveRecord::Base
  belongs_to :sender, :class_name=>'User', foreign_key: 'sender_id'
  belongs_to :recipient, :class_name=>'User', foreign_key: 'receiver_id'
end

User model:

class User < ActiveRecord::Base
  has_many :sent_messages, class: 'Message', foreign_key: 'sender_id'
  has_many :messages, class: 'Message', foreign_key: 'receiver_id' 
end

Message controller:

class MessagesController < ApplicationController

def new
  @message = current_user.sent_messages.new
end

def create
  @message = current_user.messages.new message_params
  @message.receiver_id = @recipient.id
  @message.save
end

private

def message_params
  params.require(:message).permit(:text, :receiver_id, :sender_id)
end

def set_recipient
 @recipient = User.find(params[:id])
end
end

In class attribute on associations you should specify actual class , a constant like Message . You could use "Message" too, but only in class_name .

In fact, what the message says is "you're doing something unexpected with a String", the solution is to look what strings you may have in the wrong places.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM