Ruby / Rails:friend_id未添加到友谊表中

使用Rails 4.1.4框架。 在向下面的user_friendships表添加’friend_id’时出现问题…当程序在rails中运行时,我被重定向到根(如预期的那样)并给出成功消息,即友谊已创建。 但是,当我打开数据库GUI时,我看到只有user_id被保存到user_id列中,而friend_id列总是保留为’nil’,无论是谁的朋友。 我一直在寻找高低 – 我知道它一定是简单的东西,这让我发疯了。 任何帮助深表感谢!

任何人都可以看到我可能在代码中犯的错误会阻止它被保存吗? 对于friend_id来说,这可能是一个缺失的强参数问题,如果是这样,我该如何纠正呢?

型号:

class User < ActiveRecord::Base has_many :user_friendships has_many :friends, through: :user_friendships class UserFriendship < ActiveRecord::Base belongs_to :user belongs_to :friend, class_name: 'User', foreign_key: 'friend_id' 

控制者:

 class UserFriendshipsController < ApplicationController before_filter :authenticate_user!, only: [:new] def new if params[:friend_id] @friend = User.where(profile_name: params[:friend_id]).first raise ActiveRecord::RecordNotFound if @friend.nil? @user_friendship = current_user.user_friendships.new(friend: @friend) else flash[:error] = 'Friend required.' end rescue ActiveRecord::RecordNotFound render file: 'public/404', status: :not_found end def create if params[:user_friendship] && params[:user_friendship].has_key?(:friend_id) @friend = User.where(profile_name: params[:user_friendship][:friend_id]).first @user_friendship = current_user.user_friendships.new(friend: @friend) @user_friendship.save redirect_to root_path flash[:success] = "You are now friends." #{@friend.full_name} else flash[:error] = 'Friend required.' redirect_to root_path end end 

user_friendships查看文件–new.html.erb

  

Do you really want to become friends with ?

– 个人资料页面上方表单的提交按钮

  

您有profile_name的问题。 我不知道它是什么,但它应该是一个id 。 因此,在控制器更改模型中搜索到:

 @friend = User.find_by_id(params[:user_friendship][:user_id]) 

在模板<%= f.hidden_field :friend_id, value: @friend.id %>

这对我有用

但是,如果您正在使用friendly_id gem或其他强制您使用profile_name而不是id ,您还应该在其他地方使用它,例如链接:

 new_user_friendship_path(friend_id: @user.profile_name) 

也许这会有所帮助。