我在我的Rails應用程序中設置了一個內部消息傳遞系統,並且無法將消息發送給其他用戶。Rails未定義的方法'each'for nil:NilClass
class User < ActiveRecord::Base
# messages and conversations
has_many :user_conversations
has_many :conversations, through: :user_conversations
has_many :messages
class UserConversation < ActiveRecord::Base
belongs_to :user
belongs_to :conversation
before_create :create_user_conversations
accepts_nested_attributes_for :conversation
delegate :subject, to: :conversation
delegate :users, to: :conversation
attr_accessor :to
private
def create_user_conversations
to.each do |recip|
recipient = User.find(recip)
UserConversation.create(user_id: recip, conversation_id: 1)
end
end
end
class Conversation < ActiveRecord::Base
has_many :user_conversations
has_many :users, through: :user_conversations
has_many :messages
accepts_nested_attributes_for :messages
class Message < ActiveRecord::Base
belongs_to :user_conversation
belongs_to :user
這裏是我的user_conversation_controller:
class UserConversationsController < ApplicationController
def new
@user = User.find(params[:user_id])
@conversation = @user.user_conversations.build
@conversation.build_conversation.messages.build
end
def create
@conversation = UserConversation.new(conversation_params)
@conversation.user = current_user
@conversation.conversation.messages.first.user = current_user
if @conversation.save
redirect_to user_conversation_path(current_user, @conversation)
else
flash[:error] = "There was an error"
render 'new'
end
end
private
def conversation_params
params.require(:user_conversation).permit(:to => [],
conversation_attributes: [:subject,
messages_attributes: [:body]])
end
的錯誤出現在UserConversation模型create_user_conversations方法。當我嘗試運行時
to.each do |recip|
我得到一個「未定義的方法」,每個'nil:NilClass'錯誤。然而,「到」陣列中有一個值,在這種情況下,參數是這樣的:
{"utf8"=>"✓",
"user_conversation"=>{"to"=>["2"],
"conversation_attributes"=>{"subject"=>"Hey",
"messages_attributes"=>{"0"=>{"body"=>"hey"}}}},
"commit"=>"Create User conversation",
"user_id"=>"1"}
爲什麼數組是沒有得到正確地傳遞任何想法?謝謝。
它給了我同樣的錯誤。 – bigLund8
你可以發佈你正在使用'create_user_conversations'方法嗎? – Zajn
我只在我的UserConversation Model類中使用create_user_conversations方法(如上所示)。我在使用before_create創建UserConversation之前調用它。 – bigLund8