保存关联Grape API Ruby on Rails 4

时间:2015-08-09 09:42:13

标签: ruby-on-rails ruby api grape grape-api

我想如何在Grape Gem中保存模型并进行验证? Unable to start virtual device. VirtualBox Cannot start the virtual device.

必填字段是姓名,用户名,密码和地址。 如果用户先保存,如果在配置文件模型中有验证怎么办?有什么建议让我的代码更好吗? 这是我制作的示例代码。

User has_one profile

1 个答案:

答案 0 :(得分:0)

我会添加到用户模型:

accepts_nested_attributes_for :profile

然后你可以修改葡萄:

params do
  requires :username, type: String #user
  requires :password, type: String #user

  optional :profile, type: Hash 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
  end
end

post :register do
  user = User.new params[:user]
  if user.save
    present user, with: API::Entities::User
  else
    # TODO: raise an error
  end
end

仅当个人资料有效时才会验证用户。