如何使用json POST并按用户名搜索user_id?

时间:2012-08-21 23:42:20

标签: ruby-on-rails ruby json

当我传递JSON参数:{"friend"=>{"username"=>"example"}, "auth_token"=>"n2A1Sk85MZSupXEiE1nG"}时,出现以下错误:

ActiveModel::MassAssignmentSecurity::Error (Can't mass-assign protected attributes: username)

FriendsController
def create
    @user = User.find(current_user)
    @friend = Friend.new(params[:friend])
    @friend.user_id = current_user.id
    @friend.friend_id = User.find(user.username)
    respond_to do |format|
        if @friend.save
            #flash[:notice] = 'Game was successfully created.'
            #format.html { redirect_to(@game) }
            format.json  { render :json => @friend }
        else
            #format.html { render :action => "new" }
            format.json  { render :json => @friend.errors, :status => :unprocessable_entity }
        end
    end
end

Friend Model
class Friend < ActiveRecord::Base
   attr_accessible :friend_id, :user_id
     belongs_to :user
     validates_presence_of :friend_id
     validates_presence_of :user_id
end

User Model
  class User < ActiveRecord::Base
 # Include default devise modules. Others available are:
 # :token_authenticatable, :confirmable,
 # :lockable, :timeoutable and :omniauthable
 devise :database_authenticatable, :registerable,
        :recoverable, :rememberable, :trackable, :validatable, :token_authenticatable

 before_save :ensure_authentication_token

 # Setup accessible (or protected) attributes for your model
 attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :friends_attributes, :friends
 # attr_accessible :title, :body

 has_many :games#, :dependent => :destroy
 has_many :friends, :dependent => :destroy

 validates_presence_of :username
 validates_uniqueness_of :username
end

如何从JSON接受用户名,然后又找到相应的user_id?我试图通过搜索用户名让用户与另一个用户建立联系。

1 个答案:

答案 0 :(得分:2)

您需要将username添加到Friend模型上可访问的属性列表中。所以改变:

attr_accessible :friend_id, :user_id

attr_accessible :friend_id, :user_id, :username

我相信应该这样做。