首页 > 解决方案 > 模型无效,因为创建时外键不存在

问题描述

我有一个表和另外 2 个表,每个表的 id 字段user都有外键。user当我创建一个用户时,我想在所有三个表中初始化一条记录,但是我在这样做时遇到了麻烦。user最终会创建记录,但不会创建其他两个表中的记录。经过一些调试,我发现这些模型没有保存,因为它们是无效的。错误消息说,User must exist。我正在尝试在 create 方法中完成初始化:

  def create
    logger.info "inside sessions create"
    # how do I save user first, THEN create a record associated with user in 2 tables ? 
    User.where(:id => auth_hash.uid).first_or_create do |user| # finds the matching record in users table
        user.name = auth_hash.info.name
        user.id = auth_hash.uid
        user.token = auth_hash.credentials.token
        user.secret = auth_hash.credentials.secret
      @tweetstore = Tweetstore.new() # Record I'd like to save in Table with Foreign KEY
      @tweetidstore = Tweetidstore.new() # Another Record I'd like to save in a Table with Foreign KEY
      istsvalid = @tweetstore.valid? # returns false
      istsidvalid = @tweetidstore.valid?
      error = @tweetstore.errors.full_messages #USER MUST EXIST
      @tweetstore[:user_id] = auth_hash.uid
      @tweetidstore[:user_id] = auth_hash.uid
      is_tweetstore_save = @tweetstore.save # false
      is_tweet_idstore_save = @tweetidstore.save
    end
    session[:user_id] = auth_hash.uid
    redirect_to '/'
  end

如何重组我的代码,以便User在我初始化其他依赖表时存在?optional我尝试通过将参数添加到模型(例如)来绕过问题,belongs_to :user, optional: true但后来又出现另一个错误:QLite3::ConstraintException: FOREIGN KEY constraint failed 我是 Ruby 的新手,所以请 ELI5

标签: ruby-on-railsrubypostgresql

解决方案


我放弃了该first_or_create方法,只包含了记录存在的条件。我不确定用户何时保存在我上面使用的 where 块中,所以我在将记录保存到我的依赖表之前明确保存了它。

if !User.exists?(auth_hash.uid)
  @user = User.new()
  @user.name = auth_hash.info.name
    @user.id = auth_hash.uid
    @user.token = auth_hash.credentials.token
    @user.secret = auth_hash.credentials.secret
  is_user_save = @user.save
  @tweetstore = Tweetstore.new()
  @tweetidstore = Tweetidstore.new()
  @tweetstore[:user_id] = auth_hash.uid
  @tweetidstore[:user_id] = auth_hash.uid
  is_tweetstore_save = @tweetstore.save
  is_tweet_idstore_save = @tweetidstore.save
end

推荐阅读