虚拟属性和质量分配 [英] Virtual attributes and mass-assignment

查看:122
本文介绍了虚拟属性和质量分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

开发商!我无法理解接下来的情况

developers! I can't understand next situation

例如我有模型

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

end

我可以用code是这样的:

I can use code like this:

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

但是,如果我取消attr_accessible code以上掷警告

But if I uncomment attr_accessible code above throw warning

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

我如何使用大众assigmnment虚拟属性以及模型的属性? 谢谢!

How can I use virtual attributes for mass-assigmnment together with model attributes? Thanks!

推荐答案

使用 attr_accessor ​​来添加一个变量不会自动将其添加到 attr_accessible 。如果你要使用 attr_accessible ,那么你将需要添加:人口到列表:

Using attr_accessor to add a variable does not automatically add it to attr_accessible. If you are going to use attr_accessible, then you will need to add :population to the list:

attr_accessor :population
attr_accessible :city, :isdisabled, :country_id, :population

这篇关于虚拟属性和质量分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆