我正在尝试为我的 Rails 应用程序在用户之间实现一个简单的私人消息传递功能。我认为我的模型(用户和消息)设置正确,可以发送/接收简单的私人消息。但是,现在我想添加一个似乎需要某种线程的回复功能 - 因此,我尝试使用消息表中的 conversation_id 列来跟踪这一点。有人对我如何最初设置对话 ID 有建议吗?然后为后续回复消息再次设置它?
任何帮助是极大的赞赏。此外,我认为这将有助于许多希望添加相同功能的新手程序员。谢谢。
用户模型
has_many :sent_messages, :class_name => "Message", :foreign_key => "sender_id"
has_many :received_messages, :class_name => "Message", :foreign_key => "receiver_id"
消息模型
belongs_to :sender, :class_name => "User"
belongs_to :receiver, :class_name => "User"
belongs_to :conversation, :class_name => "Message", :foreign_key => "conversation_id"
has_many :replies, :class_name => "Message", :foreign_key => "conversation_id"
after_save :set_conversation_id #only if nil (see private method below)
private
def set_conversation_id
if self.conversation_id.nil?
primary_key = self.id
self.update_attributes(:conversation_id => primary_key)
end
end
新消息表单 (messages/new.html.erb)
<%= form_for(@message) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.hidden_field :receiver_id, { :value => params[:user_id] } %>
<%= f.hidden_field :sender_id, { :value => params[:sender_id] } %>
<%= f.label :subject %>
<%= f.text_field :subject %>
<%= f.label :body %>
<%= f.text_area :body %>
<%= f.submit "Send", class: "btn btn-medium btn-primary" %>
<% end %>
消息控制器
def new
@message = Message.new
end
def create
@message = Message.new(params[:message])
if @message.save
flash[:success] = "Message sent!"
redirect_to root_path
else
render 'new'
end
end