【发布时间】:2015-08-09 09:42:13
【问题描述】:
只是想知道如何在 Grape Gem 中保存带有验证的模型?
User has_one profile
必填字段为姓名、用户名、密码和地址。 如果用户先保存,如果配置文件模型中有验证怎么办?有什么建议可以让我的代码更好吗? 这是我制作的示例代码。
desc "User registration"
params do
requires :name, type: String #profile
requires :address, type: String #profile
requires :primary_contact_number, type: String #profile
requires :other_number, type: String #profile
requires :description, type: String #profile
requires :username, type: String #user
requires :password, type: String #user
end
post :register do
# Save user?
user = User.create!({
})
Profile.create({
user: user.id
})
end
【问题讨论】:
-
Grape 不验证模型,它只是间接地与它们交互(通过 Grape::Entity 和
present/expose)返回值。您能解释一下您使用的是哪个数据库吗? -
我现在将葡萄与导轨集成在一起。所以它使用 ActiveRecord 验证。但除了验证之外,我想在创建用户到配置文件中保存一些关联,如果配置文件中有无效字段,用户也不会被保存。
-
这一切都必须使用 ActiveRecord 的特性和方法来完成,与 Grape 几乎没有任何关系。因此,如果您更改标题和标签以更加强调对 ActiveRecord 帮助的需要,您可能会得到更快/更好的响应(仍然提到 Grape,因为它可能是相关的,但它不是问题的主要话题)。我这样说是因为我确实很了解 Grape,并点击了问题以查看我是否可以提供帮助。我不能。
标签: ruby-on-rails ruby api grape grape-api