简体   繁体   English

如何在模型类中存储ID

[英]How to store an id in a model class

This should be an easy one. 这应该很容易。 I'm not sure exactly how to title the question though. 我不确定到底该如何称呼这个问题。 I have a collection of modules that can be added to my CMS (page, link, form...) they're all associated via a polymorphic association to one table that manages common things like ancestry and whether they're enabled etc... Because I'm making a 'page' for example, I handle the creation of this other table record automatically. 我有一组模块,可以添加到我的CMS(页面,链接,表单...)中,它们都通过多态关联与一个表相关联,该表管理祖先及其是否启用等常见事件。例如,因为我要创建一个“页面”,所以我会自动处理其他表记录的创建。 All I need to pass to it is the parent_id. 我需要传递给它的是parent_id。 To do this, I've created a proxy via the page model: 为此,我通过页面模型创建了一个代理:

  def parent_id=(parent_id)
    @parent_id = parent_id.blank? ? nil : parent_id.to_i
    component_instance.parent_id = @parent_id
  end

  def parent_id
    @parent_id ||= component_instance.parent_id
  end

component_instance is the polymorphic association. component_instance是多态关联。

You can see that when the parent_id is set on the page, I'm doing some magic checking to see if it's blank and if so, set the @parent_id value to nil, otherwise I turn it into an integer and then assign it through to the component_instance which will apply it as necessary when the whole page/component_instance combo is saved to the database. 您可以看到,在页面上设置了parent_id时,我正在做一些魔术检查以查看其是否为空,如果是,请将@parent_id值设置为nil,否则将其转换为整数,然后将其分配给当整个page / component_instance组合保存到数据库时,component_instance将在必要时应用它。

I had to do the blank? nil : parent_id.to_i 我必须做blank? nil : parent_id.to_i blank? nil : parent_id.to_i thing because the form selector helper expects an integer and doesn't work with a string value for the id. blank? nil : parent_id.to_i的原因,因为表单选择器帮助器需要一个整数,并且不适用于id的字符串值。

The question is, am I doing this the right way, or is there a better way to turn a string id into either nil or an integer depending on if it exists or not? 问题是,我是否以正确的方式执行此操作,还是有更好的方法将字符串id转换为nil或整数(取决于是否存在)?

I ended up delegating the setting of these 'virtual' attributes to the actual model where they were 'real': 最后,我将这些“虚拟”属性的设置委托给“真实”的实际模型:

delegate :parent_id, :parent_id=, :to => :component_instance, :allow_nil => true

Saves the need to typecast the attribute first. 无需先键入属性。

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

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