如何通过rails中的控制器设置外键?

我有一个嵌套到用户表单的地址表,但无法填写外键。 我见过人们建议使用隐藏字段,但从安全角度来看,这似乎是一个坏主意。 您如何使用控制器设置外键? 现在我收到地址用户当我尝试提交时不能出现空白错误

MVC如下

用户\ new.html.erb

Users#new

Find me in app/views/users/new.html.erb

楷模

用户

 class User < ActiveRecord::Base attr_accessible :MOS, :dateOfBirth, :ets_pcsDate, :firstName, :lastName, :middleInitial, :phoneNum, :rank, :email, :password, :password_confirmation has_secure_password has_one :address, dependent: :destroy accepts_nested_attributes_for :address before_save { |user| user.email = email.downcase } before_save :create_remember_token validates :rank, presence: true validates :firstName, presence: true, length: { maximum: 15 } validates :lastName, presence: true, length: { maximum: 20 } validates :middleInitial, presence: true, length: { maximum: 1 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[az\d\-.]+\.[az]+\z/i validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } validates :dateOfBirth, presence: true validates :MOS, presence: true validates :ets_pcsDate, presence: true validates :phoneNum, presence: true validates :password, length: { minimum: 6 } validates :password_confirmation, presence: true private def create_remember_token self.remember_token = SecureRandom.urlsafe_base64 end end 

地址

 class Address < ActiveRecord::Base attr_accessible :address, :city, :state, :zip belongs_to :user validates :address, presence: :true validates :city, presence: :true validates :state, presence: :true validates :zip, presence: true validates :user_id, presence: true end 

调节器

 class UsersController < ApplicationController before_filter :signed_in_user, only: [:index, :edit, :update, :show, :destory] before_filter :correct_user, only:[:edit, :update] before_filter :admin_user, only: :destroy def new @user = User.new @user.address.build end def create @user = User.new(params[:user]) @address = @user.build_address(params[:address]) if @user.save sign_in @user flash[:success] = "Welcome to B Troop!" redirect_to @user else render 'new' end end def show @user = User.find(params[:id]) end def index @users = User.paginate(page: params[:page]) end def edit end def update if @user.update_attributes(params[:user]) flash[:success] = "Profile updated" sign_in @user redirect_to @user else render 'edit' end end def destroy User.find(params[:id]).destroy flash[:success] = "User removed" redirect_to users_path end private def signed_in_user unless signed_in? store_location redirect_to root_path, notice: "Please sign in." end end def correct_user @user = User.find(params[:id]) redirect_to(root_path) unless current_user?(@user) end def admin_user redirect_to(root_path) unless current_user.admin? end end 

删除user_idvalidation就可以了。