I’m implementing my own user messaging feature in my application, but I’m having difficulty retaining the receiver_id.
User model:
class User < ActiveRecord::Base
has_many :tickets
has_many :sent_messages, :class_name => 'Message', :foreign_key => 'sender_id', :dependent => :destroy
has_many :received_messages, :class_name => 'Message', :foreign_key => 'receiver_id', :dependent => :destroy
end
Message model:
class Message < ActiveRecord::Base
belongs_to :sender, :class_name => 'User', :foreign_key => 'sender_id'
belongs_to :receiver, :class_name => 'User', :foreign_key => 'receiver_id'
end
Message controller:
def new
@user = User.find( params[:user_id] )
@message = Message.new(
:receiver => @user )
end
def create
@message = current_user.sent_messages.create( params[:message] )
redirect_to( tickets_path, :message => 'Message has been sent.' )
end
receiver_id in the db remains null.
Thanks for the help!
EDIT
Routes question here – ticket has users that can send messages – rails messaging
HTTP is stateless, so each request knows nothing about the one(s) before it. Thus, setting an attribute when calling
Message.newin the controller doesn’t carry over to thecreaterequest on its own—you need to have a hidden form field containing it. Assuming you’re usingform_for, it would be something like so: