0

I am trying to display data from a database via Rails ActiveRecord. Two relevant sections from my model are shown below. However, when I try to execute this, I am getting undefined methodalert_message. When I comment outrecord.alert_message, I don't get this error.

I am assuming that my JOIN is combining the two tables into one, and I think that means I could access the column named alert_message from the combined table. Why, then, is alert_message said to be undefined?

Thank you.

def maintenance_history
  MyRecord.where('my_records.org_id=?', self.org_id).order('vehicle_id')
end


self.my_history.joins("JOIN 
          alerts ON 
          my_records.id = my_record_id").group("box_id, 
          meter, alert_message, box_id").each do |record|
            # record.alerts.each do |item|
                csv << [record.id, 
                record.box.name,            
                number_with_precision(record.meter.to_s,
                         :precision => 0, :delimiter=> ','),
                record.alert_message, currency(0, record.parts, 1),           
                currency(0, record.labor, 1),
                currency(record.parts, record.labor, 1),
                record.vendor.name]
4

1 回答 1

1

In my experience you need to add a .select in order to specify the additional fields from the joined table. See http://guides.rubyonrails.org/active_record_querying.

Add

    .select(my_records.*, alerts.field1, alerts.field2)

Although you can try just alerts.* I have found issues with an id field breaking objects later.

于 2013-03-30T17:55:19.103 回答