Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 建立关系后,外键仍然为零_Ruby On Rails_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails 建立关系后,外键仍然为零

Ruby on rails 建立关系后,外键仍然为零,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,创建地址为的新用户时出现问题。我在Users和Addresses表中创建了记录,但user中address的外键仍然是nil class User < ActiveRecord::Base belongs_to :address accepts_nested_attributes_for :address end class Address < ActiveRecord::Base has_one :user end def new @user = User.

创建地址为的新用户时出现问题。我在Users和Addresses表中创建了记录,但user中address的外键仍然是nil

class User < ActiveRecord::Base
  belongs_to :address
  accepts_nested_attributes_for :address
end

class Address < ActiveRecord::Base
  has_one :user
end

def new
    @user = User.new
    @user.build_address
  end

  def create
    @user = User.new(user_params)
    if @user.save
      flash[:notice] = "Your account has been created."
      redirect_to signup_url
    else
      flash[:notice] = "There was a problem creating you."
      render :action => :new
    end
  end

private
  def user_params
    params.require(:user).permit(
      :first_name, 
      :last_name, 
      :email, 
      :password, 
      :password_confirmation,
      address_attributes: [:id, :city]
    )
  end
end
class用户:新建
结束
结束
私有的
def用户参数
参数require(:user).permit(
:名字,
:姓,
:电邮,
:密码,
:密码\u确认,
地址属性:[:id,:city]
)
结束
结束

谢谢。

您混淆了关系类型。 试试这个:

class User < ActiveRecord::Base
  has_one :address
end

class Address < ActiveRecord::Base
  belongs_to :user
end
class用户
此外,您的代码的结构也很有趣,有两个模型,然后是一些脱离上下文的方法。我希望这只是印刷错误。如果没有,则将除
地址
模型之外的所有内容放入
用户
模型。

我认为#新建#创建和#用户#参数是UsersController的操作