views:

36

answers:

2

Hi, I have a controller which is looking for a set of Contacts from the Contacts table. Currently it looks like this:

 @contacts = @campaign.contacts.find(:all, :order => "date_entered ASC") 

The method in the contact.rb (Model) is this:

 def status
  return if statuses.empty?
  a= statuses.find(:last).status << ' (' << statuses.find(:last).created_at.to_s(:long) << ')' 
  return a
 end

For the most part, if there is a value in the "status", I no longer want to display it in the view.

Right now, status is polymorphic. That might've been a dumb idea, but I wanted the concept of status to apply across different models:

class Status < ActiveRecord::Base
  attr_accessible :statusable_id, :statusable_type, :status

  belongs_to :statusable, :polymorphic => true

end

# == Schema Information
#
# Table name: statuses
#
#  id              :integer         not null, primary key
#  statusable_id   :integer
#  statusable_type :string(255)
#  status          :string(255)
#  created_at      :datetime
#  updated_at      :datetime
#

I am assuming that if I can add that condition to the @contacts instance, that would take care of it. But I don't know how to write that condition in the controller on the .find method (if that is the right way to do it).

thanks.

+2  A: 

I am assuming that contact has_many statuses . I am not sure about the rest of the app , but from the code that you have given above , it seems that you are interested in only the last status , and thus you might be better off making status and attribute instead of a has_many association .
However , assuming that for some other requirement you do need the has_many association , in that case what you have done seems reasonable .

NM
Hi, but what do I do as a condition?I'm not sure I will stay has_many...I *think* this will allow me to trace any changes as the status changes...but not sure.I was also thinking of making multiple models all statusable via polymorphic...rather than having a separate attribute. But it would be much simpler if I did it.
Angela
A: 

To expand on NM's answer, just why not make a contact has_one latest_status relationship, and then find using the :join option? It's documented in the Active Record Base page at http://api.rubyonrails.org/classes/ActiveRecord/Base.html, just search for :joins.

If you search the joined table, and you've defined the relationship already to be the latest status, then you'd have what you want, right?

jasonpgignac
Hi I still don't have the condition....would I use status is ? NULL? blank?
Angela
Here's the error I get:SQLite3::SQLException: no such column: status.id
Angela
I don't have the SQLite3 docs in front of me, but I believe the where clause to match a null value would be "WHERE status.field IS NULL". Is that what you're asking?
jasonpgignac
yeah, I tried that...but let me try again...
Angela