我试图在2位用户之间建立友谊,而我正在使用tutorial
我将此作为我的friendships_controller.rb,
def create
@friendship = current_user.friendships.build(:friend_id => params[:friend_id])
if @friendship.save
flash[:notice] = "Added friend."
redirect_to root_url
else
flash[:error] = "Unable to add friend."
redirect_to root_url
end
end
在Angular中我有这个功能,
$scope.addFriend = function (user) {
$scope.user = user
console.log ($scope.user)
createFriend.create({
friend_id: $scope.user.id
})
}
这是我的Angular服务中的创建方法,
app.factory('createFriend', ['$http', function($http) {
return {
create: function() {
return $http.post('/friendships.json');
}
};
}])
当我添加一个朋友时,我在我的rails控制台中得到了这个,
Started POST "/friendships.json" for 127.0.0.1 at 2015-12-29 12:51:59 +0100
Processing by FriendshipsController#create as JSON
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
(0.1ms) begin transaction
SQL (9.9ms) INSERT INTO "friendships" ("user_id", "created_at", "updated_at") VALUES (?, ?, ?) [["user_id", 1], ["created_at", "2015-12-29 11:51:59.550777"], ["updated_at", "2015-12-29 11:51:59.550777"]]
(17.6ms) commit transaction
Redirected to http://localhost:3000/
Completed 302 Found in 39ms (ActiveRecord: 27.7ms)
从控制台输出中可以看到,friend_id
参数丢失。
它已添加到数据库中,
create_table "friendships", force: :cascade do |t|
t.integer "user_id"
t.integer "friend_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
当我在我的rails控制台中运行Friendship.all
时,我得到了,
<Friendship id: 1, user_id: 1, friend_id: nil, created_at: "2015-12-29 11:36:46", updated_at: "2015-12-29 11:36:46">
为什么friend_id
参数未被使用的任何想法?
答案 0 :(得分:1)
您需要将参数从createFriend.create
传递到$http.post
。如果您查看documentation,$http.post
将url作为第一个参数,请求内容作为第二个参数。现在,{friend_id: $scope.user.id}
被忽略了。下面的代码(未经测试)应该可以解决问题。
app.factory('createFriend', ['$http', function($http) {
return {
create: function(data) {
return $http.post('/friendships.json', data);
}
};
}])