1

当我传递 JSON Parameters:{"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?我试图通过搜索用户名来允许用户与另一个用户成为朋友。

4

1 回答 1

2

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

attr_accessible :friend_id, :user_id

attr_accessible :friend_id, :user_id, :username

我相信应该这样做。

于 2012-08-21T23:50:34.250 回答