【问题标题】:ActiveModel::MassAssignmentSecurity::Error: / Can't mass-assign protected attributes: userActiveModel::MassAssignmentSecurity::Error: / Can't mass-assign protected attributes: user
【发布时间】:2013-03-26 14:51:38
【问题描述】:

我正在学习 Michael Hartl 的 Ruby on Rails 教程,并且正在为用户建模。 User_spec.rb 测试失败,我对错误的理解是,由于某种原因,这些属性没有被读取为可访问的,尽管代码说它们应该是。我也完成了 rake db:test:prepare 。任何帮助将不胜感激。

用户模型很简单。

app/models/user.rb

class User < ActiveRecord::Base
  attr_accessible :name, :email

end

在 spec/models/user_spec.rb 的测试是这样的:

require 'spec_helper'

describe User do

    before { @user = User.new(user: "Example User", email: "user@example.com") }

    subject { @user }

    it { should respond_to(:name) }
    it { should respond_to(:email) }

end

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    应该是name 而不是user...请检查以下内容

    require 'spec_helper'
    
    describe User do
    
      before { @user = User.new(name: "Example User", email: "user@example.com") }
    
      subject { @user }
    
      it { should respond_to(:name) }
      it { should respond_to(:email) }
    end
    

    您在使用Example Useruser 创建新记录时出错。应该是name

    【讨论】:

    • 我很想给你一个支持,但缺乏这样做的声誉! :(
    • Vinay——我会给你一个很好的答案和记录。堆栈溢出要求我在接受我的选择之前拥有 15 的声誉。可悲的是,我的声誉是 2。:(
    • 谢谢@Vinay!那成功了,我现在可以投票了!非常感谢!
    【解决方案2】:

    您想通过批量分配更新的任何内容都需要在您的attr_accessible 中。

    改变这个

    class User < ActiveRecord::Base
      attr_accessible :name, :email
    
    end
    

    到这里:

    class User < ActiveRecord::Base
      attr_accessible :name, :email, :user
    
    end
    

    虽然user 似乎不是正确的属性名称。是不是应该是username

    【讨论】:

    • 他不想为:user 添加新的attr_accessible。因为他在创建新记录时错误地将user而不是name
    猜你喜欢
    • 1970-01-01
    • 2012-04-16
    • 2013-11-27
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多