简体   繁体   English

Rails-无法创建具有与该类同名的属性的记录

[英]Rails - Can't create a record that has an attribute with the same name of the class

I'm having troubles trying to create (or even update) a database record, because both the parent class name and the name of an attribute are equal. 我在尝试创建(甚至更新)数据库记录时遇到了麻烦,因为父类名称和属性名称都相等。 I'm using a consolidated database, so I can't alter the tables. 我正在使用统一数据库,因此无法更改表。

I have a class Period with an attribute 'period'. 我有一个带有属性'period'的类Period。 One period has many tax scales. 一个时期有很多税率。

#period model
has_many :tax_scales, 
    foreign_key: 'period', 
    primary_key: 'period'

#tax_scale model
belongs_to :period, 
    foreign_key: :period,
    primary_key: :period

So, when I use this in my tax_scale view: 所以,当我在tax_scale视图中使用它时:

#new.html.haml
= f.label :period
= f.number_field :period

I get this error: 我收到此错误:

Period(#97477176) expected, got String(#8598408) 预期期间(#97477176),得到字符串(#8598408)

My controller params are: 我的控制器参数是:

params.require(:tax_scale).permit(:minimum, :maximum, ..., :period)

How can I edit (or create) a tax_scale record succesfully? 如何成功编辑(或创建)tax_scale记录?

I found the solution: use methods using self[:attribute], to be sure the attribute is accessed 我找到了解决方案:使用使用self [:attribute]的方法,确保可以访问属性

#tax_scale model
def current_period
  self[:period]
end

def current_period=(p)
  self[:period] = p
end

#new.html.haml
= f.label :current_period
= f.number_field :current_period

Notice I have to use self[:period] and not self.period, because the second one is still accessing the parent record, not the attribute. 注意,我必须使用self [:period]而不是self.period,因为第二个仍在访问父记录,而不是属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM