假设我有一个模型用户,其属性为:name:string,email:string。如果我在线或在控制台中创建用户并保存该用户,则会为该用户提供ID。但是,如果我(通过R)将用户数据发送到我的posgresql数据库,则用户将拥有属性但没有用户ID。当我将数据导入模型时,我需要做些什么来确保用户具有ID?
Rails控制台用户ID检查
2.2.1 :002 > User.first.id
User Load (12.6ms) SELECT "Users".* FROM "Users" LIMIT 1
=> nil
R导入代码
require("RPostgreSQL")
pw <- {
"password"
}
con <- dbConnect(drv, dbname = "my_database_production",
host = "localhost", port = 5432,
user = "user_name", password = pw)
dbExistsTable(con, "users")
dbWriteTable(con, "users",
value = new_data, overwrite=TRUE)
dbDisconnect(con)
rm(pw)
答案 0 :(得分:1)
确保我已经做到了这一点:你想要添加用户,并让动作返回新的用户ID,这样你就可以通过某种方式引用它们了,可能是在函数的后期。
我不知道在Rails中是否有内置函数来执行此操作,但如果R应用程序需要知道新用户的用户ID,则可以执行以下操作:
1)两步:插入,然后select id from Users where [blah]
。使用dbWriteTable()
并不能做到这一点:当您编写新表时,现有用户表会被覆盖。我假设id
是serial
类型或来自服务器端序列,即由数据库分配。
2)使用带有RETURNING
子句的插入查询。警告:我不是Rails专家,所以我们可能需要做其他桌面魔术。
require(DBI) # for dbQuoteString()
users <- data.frame(stringsAsFactors=FALSE,
name=c("Alice", "Bob", "Claire"),
email=c("alice@foo.com", "bob@bar.com", "cc@baz.com")
)
# protect against names that have quotes, like O'Toole.
# and protect against SQL injection at the same time.
# If we had any integer or float values, protect against
# sqli like this:
# num_val <- as.numeric(num_val)
# int_val <- as.integer(int_val)
users$name <- dbQuoteString(ANSI(), users$name)
users$email <- dbQuoteString(ANSI(), users$email)
qry <- "INSERT INTO Users (name, email) VALUES "
# now build the "values" string.
vals <- apply(users,1,paste,collapse=",")
vals <- paste("(",vals,")", collapse=", ")
qry <- paste(qry, vals)
# in this example, we return all the columns we've inserted,
# plus the user id.
qry <- paste(qry, "RETURNING name, email, id")
res <- dbGetQuery(con, qry)