【发布时间】:2018-04-23 23:40:46
【问题描述】:
我在 RoR 中遇到了这个错误:
于 2017 年 11 月 10 日 15:03:09 -0200 开始为 127.0.0.1 发布 POST "/conversations?person_id=3" ConversationsController#create as JS 处理 参数:{"person_id"=>"3"} 1ms 内完成 500 Internal Server Error (ActiveRecord: 0.0ms)
NoMethodError(nil:NilClass 的未定义方法 `id'):
app/controllers/conversations_controller.rb:3:in `create'
我的对话控制器:
class ConversationsController < ApplicationController
def create
@conversation = Conversation.get(current_person.id, params[:person_id])
add_to_conversations unless conversated?
respond_to do |format|
format.js
end
end
def close
@conversation = Conversation.find(params[:id])
session[:conversations].delete(@conversation.id)
respond_to do |format|
format.js
end
end
private
def add_to_conversations
session[:conversations] ||= []
session[:conversations] << @conversation.id
end
def conversated?
session[:conversations].include?(@conversation.id)
end
end
对话模型:
class Conversation < ApplicationRecord
has_many :messages, dependent: :destroy
belongs_to :sender, foreign_key: :sender_id, class_name: Person
belongs_to :recipient, foreign_key: :recipient_id, class_name: Person
validates :sender_id, uniqueness: { scope: :recipient_id }
scope :between, -> (sender_id, recipient_id) do
where(sender_id: sender_id, recipient_id: recipient_id).or(
where(sender_id: recipient_id, recipient_id: sender_id)
)
end
def self.get(sender_id, recipient_id)
conversation = between(sender_id, recipient_id).first
return conversation if conversation.present?
create(sender_id: sender_id, recipient_id: recipient_id)
end
def opposed_person(person)
person == recipient ? sender : recipient
end
end
会话创建.js
var conversations = $('#conversations-list');
var conversation = conversations.find("[data-conversation-id='" + "<%= @conversation.id %>" + "']");
if (conversation.length !== 1) {
conversations.append("<%= j(render 'conversations/conversation', conversation: @conversation, person: current_person) %>");
conversation = conversations.find("[data-conversation-id='" + "<%= @conversation.id %>" + "']");
}
conversation.find('.panel-body').show();
var messages_list = conversation.find('.messages-list');
var height = messages_list[0].scrollHeight;
messages_list.scrollTop(height);
【问题讨论】:
-
current_person为零。找出原因。 -
在 AJAX 请求期间会发生这种情况吗?
-
抱歉,什么是 AJAX?此代码是 RoR 中实时信使应用程序的一部分。当我点击某人开始对话时会发生错误。
标签: ruby-on-rails methods null