0

我正在我的应用程序中实现我自己的用户消息传递功能,但我很难保留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在数据库中保持为空。

谢谢您的帮助!

编辑

此处的路由问题 -票证有可以发送消息的用户 - rails 消息传递

4

1 回答 1

1

HTTP 是无状态的,因此每个请求对它之前的请求一无所知。因此,在控制器中调用时设置属性Message.new并不会单独传递给create请求——您需要有一个包含它的隐藏表单字段。假设您正在使用form_for,它会是这样的:

<%= f.hidden_field :receiver_id %>
于 2012-05-01T05:05:34.047 回答