ruby-on-rails - 模型无效,因为创建时外键不存在
问题描述
我有一个表和另外 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
解决方案
我放弃了该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
推荐阅读
- javascript - 通过调用返回要打开的jsp名称的java方法打开新标签jsp
- ios - 删除collectionView中特定位置的特定单元格
- julia - 如何在 Julia 中表示抽象时间
- python - 由于版本问题,安装 virt-manager 时出错
- javascript - NodeJS:发送电子邮件(例如向我的应用程序的用户发送通知)无需对其进行身份验证或接收电子邮件
- cmake - 如何在 cmake 中正确链接库?
- python - PyCharm 中未解决的引用错误,即使代码运行正常
- c# - 如何反转 Array.Sort 的方向 - C#
- javascript - 当我点击下一个按钮时,上一个问题必须用反向动画删除,下一个问题必须用打字效果动画显示
- c - 为什么FD_ISSET()要在accept()建立连接之前判断