我尝试设置我的rails应用,以便当用户访问www.example.com/personal_messages/new时,它不会创建新帐户,而是在用户提交时。但问题是,如果移动User.create函数,我将收到错误。有解决方法吗?
personal_messages controller
class PersonalMessagesController < ApplicationController
before_action :check_receiver!, only: [:new, :create]
def new
redirect_to conversation_path(@conversation) and return if @conversation
@personal_message = current_user.personal_messages.build
end
def create
@conversation ||= Conversation.create(author_id: cookies[:user_id],
receiver_id: @receiver)
@personal_message = current_user.personal_messages.build(personal_message_params)
@personal_message.conversation_id = @conversation.id
@personal_message.save!
flash[:success] = "ok!"
redirect_to conversation_path(@conversation)
end
private
def personal_message_params
params.require(:personal_message).permit(:body)
end
def check_receiver!
@ip = request.remote_ip
if cookies[:user_id].blank?
@user = User.create(email: "thinkrtcvisitor-#{rand(999999)}@visitor.com", ip_address: @ip, password: '12345678', password_confirmation: '12345678')
@user.save!
cookies.permanent[:user_id] = @user.id
cookies.permanent[:current_user_cookie] = User.find_by_id(cookies[:user_id])
session[:user_id] = @user.id
end
@receiver = cookies[:site_id]
@conversation = Conversation.between(cookies[:user_id], @receiver)[0]
end
end
答案 0 :(得分:0)
使用
@personal_message = current_user.personal_messages.new
而不是
@personal_message = current_user.personal_messages.build
在new
行动中。