Ian Ellis Ian Ellis - 1 year ago 116
Ruby Question

Ruby on Rails: User helper method to read attribute

I'm trying to use a helper method to determine the value of an attribute for several records. Here is the basic function I am trying to get working (from the view):

<% if Baseline.where(subject_id: sub.subject_id).first.crf_status(crf) == 1 %>
<td bgcolor="#98FB98" >
<% else %>

My helper function is crf_status(crf), and it looks like this:


def crf_status(crf)
case crf
when Baseline then 'baseline_status'
when FollowUp3Week then 'follow_up_3_week'

So a working example would be if crf_status(Baseline) would return:

<% if Baseline.where(subject_id: sub.subject_id).first.baseline_status == 1 %>
<td bgcolor="#98FB98" >
<% else %>

Right now, the error is 'undefined method 'crf_status' for Baseline'. So based on what I've read, perhaps I have to reference ApplicationHelper in each controller? That doesn't sound right. Please let me know what you think.


edit. I forgot to make this more clear: crf_status(crf) is being passed an object from an array [Baseline, FollowUp3Week...].

The actual line starts with it as well -> if crf.where(subject_id:...

Answer Source

If you want to return a method that is to be called in the context, use the .send method.

Baseline.where(subject_id: sub.subject_id).first.send(crf_status(crf))

Whatever is returned from your method will be executed. This is a great metaprogramming example. You want to test against the class of the instance, so use the .class method on your case line. You'll want to return symbols not strings though, so do this:

def crf_status(crf)
    case crf.class
    when Baseline then :baseline_status
    when FollowUp3Week then :follow_up_3_week
    else :default
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download