views:

34

answers:

0

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. All I need to pass to it is the 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.

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.

I had to do the 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.

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?