加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 无法批量分配受保护的属性attr_accessor和attr_accessib

发布时间:2020-12-17 03:16:12 所属栏目:百科 来源:网络整理
导读:在rails 2.3.11中,我在模型中有以下内容 attr_accessor :person_id 并在控制器中 @project.person_id = current_user.id 现在,我正在使用rails 3.2.11转换它,我正在接受 Can't mass-assign protected attributes: person_id 所以我改变了模型,我从attr_acces
在rails 2.3.11中,我在模型中有以下内容

attr_accessor :person_id

并在控制器中

@project.person_id = current_user.id

现在,我正在使用rails 3.2.11转换它,我正在接受

Can't mass-assign protected attributes: person_id

所以我改变了模型,我从attr_accessor删除了:person_id并添加到下面的行

attr_accessible :person_id

但我是控制器中的person_id,在这里

@project.person_id = current_user.id

我现在得到这个

NoMethodError in ProjectsController#create

undefined method `person_id=' for #<Project:0x19cc51a>

任何想法或帮助,我该如何解决这个问题?如何处理attr_accessor和amp; attr_accessible?

解决方法

attr_accessor:person_id和attr_accessible:person_id不一样.

attr_accessor是Ruby方法.简而言之,它是方法的捷径:

def person_id
  @person_id
end

def person_id=(value)
  @person_id = value
end

attr_accessible是Rails方法.获取允许批量分配的属性列表.你可以阅读约here.

因此,在您的情况下,您需要它们.

attr_accessor :person_id
attr_accessible :person_id

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读