我有两个数据库表Users和Accounts,当创建新用户时,他们将用于登录的主电子邮件地址存储在Users表中。我想做的是在Accounts表中存储他们的主电子邮件地址的副本,因为这个表将用于存储该用户的电子邮件地址。
我在我的users_controller
中尝试了以下操作:
class UsersController < ApplicationController
def index
@users = User.all
end
def show
@user = User.find(params[:id])
end
def new
@user = User.new
end
def edit
@user = User.find(params[:id])
end
def create
@user = User.new(user_params)
if @user.save
session[:user_id] = @user.id
@account = Account.new(email: params[:primaryemailaddress], user_id: session[:user_id])
redirect_to @user
else
render 'new'
end
end
def update
@user = User.find(params[:id])
if @user.update(user_params)
redirect_to @user
else
render 'edit'
end
end
def destroy
@user = User.find(params[:id])
@user.destroy
redirect_to users_path
end
private
def user_params
params.require(:user).permit(:title, :firstname, :surname, :housenumber, :street, :city, :postcode, :organisation, :primaryemailaddress, :password)
end
end
在我的User
模型中:
class User < ActiveRecord::Base
has_many :accounts
accepts_nested_attributes_for :accounts
validates :primaryemailaddress, presence: true
has_secure_password
end
因此,正如您在users_controller
中的create
方法中所看到的,我试图使用用户在注册表单上输入的主要电子邮件地址在Accounts表中创建一个新记录。
谁能告诉我我哪里错了?
请尝试以下修改
def create
@user = User.new(user_params)
if @user.save
session[:user_id] = @user.id
@account = Account.create(email: params[:user][:primaryemailaddress], user_id: session[:user_id])
redirect_to @user
else
render 'new'
end
end