1

I have a very complicated Rails (v 3.2) model that is doing a manual select over multiple tables. This works great for getting all the data I need to display my Model. However, when my data doesn't exist and I have to create a virtual object, these columns don't exist on my model. For the life of me I can't figure out a way to support both virtual and actual columns on a model.

It is a lot more complicated than this, but this is the general select I currently have:

class MyObject < ActiveRecord::Base

  attr_accessible :apples, :bananas, :oranges

  def self.get(id)
    select("my_objects.*, table1.apples, table2.bananas, table3.oranges")
      .joins("left outer join table1 on something
              left outer join table2 on something
              left outer join table2 on something")
      .where(:my_object => id)
  end
end

This works great for what I need it to display when id exists. However, in some cases id doesn't exist and I have to display a virtual (or default) object.

I thought I could simply do something like this for that virtual object:

@my_object = MyObject.new({:apples => 1,
                           :bananas => 50,
                           :oranges => 10})

But of course, in the view when I do @my_object.apples I get an error because MyObject doesn't actually have those columns:

ActionView::Template::Error (unknown attribute: apples)

The next step I took was to add attr_accessor to the MyObject model:

attr_accessor :apples, :bananas, :oranges

That works perfect for the virtual version of MyObject. But now, when trying to display a real version of the object, all my apples, bananas, and oranges are nil! I assume this is because the attr_accessor getters and setters are overridding what the select is returning.

How can I support both virtual and actual attributes on this model?

p.s. I've tried multiple ways of using method_missing along with define_method, but have been unable to get anything that is successful.

3
  • This might be because this is an example you've constructed, but I'm confused about why you mention both apple and apples, banana and bananas, and cup and oranges... what are the actual methods you'd like to be able to call on an instance of MyObject? Sep 25, 2013 at 21:14
  • @carolclarinet - Sorry, that was due to an edit where I missed all the changes. It is fixed now. The core problem is that sometimes the attributes exist and sometimes they do not Sep 25, 2013 at 21:22
  • Awesome, that clears it up a lot. Thank you! Sep 25, 2013 at 23:11

3 Answers 3

1

Interesting problem.

One way is to define a setter method for virtual attribs like so

# MyObject.rb

def set_virtual_attribs=(hsh)
 hsh.map{|key,value|  self[key] = value}
end

then you can create a virtual object like so

@my_object = MyObject.new(:set_virtual_attribs => {
                           :apples => 1,
                           :bananas => 50,
                           :oranges => 10
                         })

The virtual attributes should now be available as @my_object.apples and this will not override any attribute methods for actual objects unless the set_virtual_attribs is called.

6
  • This works! However, it does have 2 side effects I don't care much for. First, I now get this warning DEPRECATION WARNING: You're trying to create an attribute 'apples'. Writing arbitrary attributes on a model is deprecated. Please just use 'attr_writer' etc.. Second, I had to change my view layer to access the attributes like a hash rather than through a method. I'm going to wait a bit longer before I mark it as the solution. Sep 25, 2013 at 22:53
  • 1
    They should be accessible via methods like @my_objects.apples, I tried it my console.
    – tihom
    Sep 25, 2013 at 22:56
  • I stand corrected, it is accessible via method. Any thoughts on bypassing the deprecation warning? Sep 25, 2013 at 23:01
  • one option you can try is to use write_attribute(key) instead of self[key]
    – tihom
    Sep 25, 2013 at 23:56
  • using write_attribute(key) still give the deprecation warning. I feel like the only way to get around it is some combination of attr_writer with missing_method. This works good for now. Sep 26, 2013 at 13:07
1

I would recommend looking into the Null Object Pattern; I think ideas along those lines will help in your case.

The general idea is that instead of having nil checks everywhere, you create an object that can stand in for the original object with some sensible defaults.

I'm assuming that something outside your class MyObject definition is deciding when id doesn't exist and therefore you need to do the @my_object = MyObject.new({:apples => 1,... call. Instead of creating an instance of MyObject there, you could have a different class like:

class MyNilObject
  def apples
    1
  end

  def bananas
    50
  end

  def oranges
    10
  end
end

and then instead do @my_object = MyNilObject.new. If it's a requirement that you be able to set these default values dynamically, you can have a def initialize that takes a hash and assigns attributes and has attr_readers.

This class would be a Plain Old Ruby Object that wouldn't have any database persistence. It would need to implement any other methods that your view calls on an instance of MyObject.

I'm not sure what you do in this case after rendering the object, so you may need to implement a method like create on this object that would convert it into an instance of MyObject and save it in the database, potentially.

1
  • I do like this option. The values for apples, bananas, and oranges are not static like your example, but that could easily be changed. However, I feel like @tihom has the better answer for the problem, rather than re-factoring Sep 26, 2013 at 13:09
0

You could override the accessor methods in the models:

class MyObject < ActiveRecord::Base

  def apples
    read_attribute(:apples) || 1
  end

  # etc ....
end
2
  • I think this answer is simplest if the default value does not change and you are ok with making this attribute accessible for all objects new or old.
    – tihom
    Sep 25, 2013 at 23:51
  • This is simple, but I have to be able to change the values on the virtual column. I see how saying default values led to this conclusion and I'm sorry. There are around 10-25 different MyObjects in this view, each with different values for apples, bananas, and oranges. Sep 26, 2013 at 12:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.