在我的Rails应用程序中,我为使用的iOS应用程序制作了api。
我有user
模型与profile
:
class User < ActiveRecord::Base
has_one :personal_profile
accepts_nested_attributes_for :personal_profile
end
class PersonalProfile < Profile
belongs_to :user
end
users_controller.rb
看起来像这样:
class Api::V1::UsersController < Api::V1::ApiController
before_filter :authenticate_api_user, only: [:show, :update]
def create
@user = User.new(user_params)
if @user.save
@user
else
render json: { errors: @user.errors.full_messages }, status: 422
end
end
def show
@user
end
def update
if @user.update(user_params)
@user
else
render json: { errors: @user.errors.full_messages }, status: 422
end
end
private
def user_params
params.require(:user).permit(:name, :email, :birthday, :gender, :password, :password_confirmation, personal_profile_attributes: [:website, :location, :description, :tagline, :tag_tokens, :image, :image_cache])
end
def authenticate_api_user
authenticate_or_request_with_http_token do |token, options|
@user = User.find_by(auth_token: token)
end
end
end
当我做这样的看跌请求时:
curl -H 'Authorization: Token token=AUTH_TOKEN' -H 'Content-Type: application/json' -X PUT -d '{"user": {"name": "Frank", "personal_profile_attributes": { "tagline": "New tagline" }}}' http://localhost:3000/api/user
我收到了这个回复:
{"errors":["Personal profile title can't be blank."]}
就像服务器无法识别我的参数:
Started PUT "/api/user" for ::1 at 2016-01-19 10:16:33 +0100
Processing by Api::V1::UsersController#update as JSON
Parameters: {"user"=>{"name"=>"Frank", "personal_profile_attributes"=>{"tagline"=>"New tagline"}}}
User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."auth_token" = $1 LIMIT 1 [["auth_token", AUTH_TOKEN]]
(0.8ms) BEGIN
PersonalProfile Load (1.2ms) SELECT "profiles".* FROM "profiles" WHERE "profiles"."type" IN ('PersonalProfile') AND "profiles"."user_id" = $1 ORDER BY title asc LIMIT 1 [["user_id", 1]]
SQL (1.3ms) UPDATE "profiles" SET "user_id" = $1, "updated_at" = $2 WHERE "profiles"."id" = $3 [["user_id", nil], ["updated_at", "2016-01-19 09:16:33.629907"], ["id", 1]]
User Exists (1.3ms) SELECT 1 AS one FROM "users" WHERE (LOWER("users"."email") = LOWER('d@friis.me') AND "users"."id" != 1) LIMIT 1
(0.8ms) ROLLBACK
Completed 422 Unprocessable Entity in 19ms (Views: 0.3ms | ActiveRecord: 6.5ms)
我为网络应用设置了另一个控制器设置,这是非常标准的,并且工作得很好!
非常感谢任何帮助!
答案 0 :(得分:0)
好的,问题是我没有为请求参数传递关联记录的ID
。这意味着使用我试图更新的属性创建了一个新的关联记录。
设置ID
解决了问题并按预期更新了记录。
{
"user" => {
"personal_profile_attributes" => {
"id" => 1,
"tagline" => "New tagline"
}
}
}