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

ruby-on-rails – 虚拟属性和批量分配

发布时间:2020-12-16 19:34:20 所属栏目:百科 来源:网络整理
导读:开发商!我无法理解下一个情况 例如我有模型 class Pg::City ActiveRecord::Base belongs_to :country #virtual accessors attr_accessor :population #attr_accessible :city,:isdisabled,:country_idend 我可以使用这样的代码: c = Pg::City.new({:popula
开发商!我无法理解下一个情况

例如我有模型

class Pg::City < ActiveRecord::Base
   belongs_to :country  
   #virtual accessors
   attr_accessor :population
   #attr_accessible :city,:isdisabled,:country_id

end

我可以使用这样的代码:

c = Pg::City.new({:population=>1000})
puts c.population
1000

但如果我取消注释上面的attr_accessible代码抛出警告

WARNING: Can't mass-assign protected attributes: population

如何将虚拟属性与模型属性一起用于质量分配?
谢谢!

解决方法

使用attr_accessor添加变量不会自动将其添加到attr_accessible.如果您打算使用attr_accessible,那么您需要在列表中添加:population:
attr_accessor :population
attr_accessible :city,:country_id,:population

(编辑:李大同)

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

    推荐文章
      热点阅读