receiver_id 不保存 - rails 消息传递 [英] receiver_id not saving - rails messaging
问题描述
我正在我的应用程序中实现我自己的用户消息传递功能,但我很难保留 receiver_id
.
I'm implementing my own user messaging feature in my application, but I'm having difficulty retaining the receiver_id
.
用户模型:
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
消息模型:
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
消息控制器:
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
保持为空.
receiver_id
in the db remains null.
感谢您的帮助!
编辑
这里的路由问题 - ticket 有可以发送消息的用户- Rails 消息传递
推荐答案
HTTP 是无状态的,因此每个请求对其之前的请求一无所知.因此,在控制器中调用 Message.new
时设置属性不会自行传递到 create
请求 - 您需要有一个包含它的隐藏表单字段.假设您正在使用 form_for
,它会是这样的:
HTTP is stateless, so each request knows nothing about the one(s) before it. Thus, setting an attribute when calling Message.new
in the controller doesn't carry over to the create
request on its own—you need to have a hidden form field containing it. Assuming you're using form_for
, it would be something like so:
<%= f.hidden_field :receiver_id %>
这篇关于receiver_id 不保存 - rails 消息传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!