【问题标题】:Can't mass-assign protected attributes attr_accessor and attr_accessible无法批量分配受保护的属性 attr_accessor 和 attr_accessible
【发布时间】:2013-05-07 22:24:09
【问题描述】:

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 和 attr_accessible?

【问题讨论】:

  • 把它们都放在attr_accessible :person_id 中; attr_accessor :person_id
  • @ShawnBalestracci 如果我同时放置 attr_accessible :person_idattr_accessor :person_id,我收到了Can't mass-assign protected attributes: person_id
  • 批量分配错误不是来自此行:@project.person_id = current_user.id,因为这不是批量分配。
  • @Arjan 是的,你是对的,我明白了,因为我在位置的型号中使用了那个 person_id。

标签: ruby ruby-on-rails-3.2


【解决方案1】:

attr_accessor :person_idattr_accessible :person_id 不一样。

attr_accessorRuby 方法。简而言之,它是方法的快捷方式:

def person_id
  @person_id
end

def person_id=(value)
  @person_id = value
end

attr_accessibleRails 方法。获取允许批量分配的属性列表。你可以阅读here

因此,在您的情况下,您需要两者。

attr_accessor :person_id
attr_accessible :person_id

【讨论】:

  • 如果我同时放置 attr_accessible :person_id ; attr_accessor :person_id,我得到 Can't mass-assign protected attributes: person_id
  • 嗯。检查application.rb 中的config.active_record.whitelist_attributes = true。然后尝试玩true/false
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-04
  • 1970-01-01
相关资源
最近更新 更多