belongs_to like virtual attribute

25 views
Skip to first unread message

kevinpfromnm

unread,
Jul 26, 2011, 2:28:55 PM7/26/11
to hobo...@googlegroups.com
I'm wondering if anyone has done or knows of a simple way to implement an attr_accessor that behaves like a belongs_to association.  I'm making a lifecycle transition and need to pass a parameter that is an id to another model and thought if I could define it with a type like an association, I could get the desired behavior without having to touch the view.

Matt Jones

unread,
Jul 26, 2011, 5:42:12 PM7/26/11
to hobo...@googlegroups.com

On Jul 26, 2011, at 2:28 PM, kevinpfromnm wrote:

> I'm wondering if anyone has done or knows of a simple way to implement an attr_accessor that behaves like a belongs_to association. I'm making a lifecycle transition and need to pass a parameter that is an id to another model and thought if I could define it with a type like an association, I could get the desired behavior without having to touch the view.

I've used the :params => :some_belongs_to_association trick before in transitions (very slick) but not with a virtual attribute. Here's a first swipe at what should work:

(in the model):

attr_accessor :some_field_name, :type => ModelClass
def some_field_name=(v)
@some_field_name = v.is_a?(ModelClass) ? v : ModelClass.find(v)
end

Declare an input for ModelClass that makes a dropdown list - select-one *may* do the right thing here, but you'll have to pass an explicit list of options to it or it'll blow up trying to do a reflection.

--Matt Jones

kevinpfromnm

unread,
Jul 26, 2011, 6:59:10 PM7/26/11
to hobo...@googlegroups.com
Hmm.. if I have to make the input for each model I'm not saving much from what I already got.  I had to make a custom view to map the options (yes, it blew up on the reflection).  I was just hoping there'd be a simple way to get the hobo magic on the view.

Matt Jones

unread,
Jul 26, 2011, 7:36:33 PM7/26/11
to hobo...@googlegroups.com

On Jul 26, 2011, at 6:59 PM, kevinpfromnm wrote:

> Hmm.. if I have to make the input for each model I'm not saving much from what I already got. I had to make a custom view to map the options (yes, it blew up on the reflection). I was just hoping there'd be a simple way to get the hobo magic on the view.

It should be possible to declare an input tag for ActiveRecord::Base and use some name_attribute mojo to build a generic input, but there's a serious magic-drought when there's not a reflection, etc to work with. :)

--Matt Jones

Reply all
Reply to author
Forward
0 new messages