2

Experimenting an issue trying to achieve a virtual attributes of a model in another controller. Is there a way to do it?

Here is the virtual attributes:

def montant
  self.facture_details.sum(:montant_detail)
end

def paiements
  self.facture_paiements.sum(:montant)
end

def facture_statut
  if self.paiements < self.montant
  then
    "Ouverte"
  else
    "Payée"
  end
end

And in another controller I'm trying to do:

 @factures = Facture.find(:all, :conditions => {:facture_statut => 'Ouverte'})

When I do this I got an error:

SQLite3::SQLException: no such column: factures.facture_statut: SELECT "factures".* FROM "factures" WHERE "factures"."facture_statut" = 'Ouverte'

Is there someone to help me with this?

Thanks

Update; here is the full model:

class Facture < ActiveRecord::Base
  has_many :facture_details, :dependent => :destroy
  has_many :facture_paiements
  accepts_nested_attributes_for :facture_details, :allow_destroy => true
  accepts_nested_attributes_for :facture_paiements
  attr_accessor :facture_statut
  attr_accessor :montant
  attr_accessor  :paiements
  def montant
    self.facture_details.sum(:montant_detail)
  end
  def paiements
    self.facture_paiements.sum(:montant)
  end
  def facture_statut
    if self.paiements < self.montant
      then
      "Ouverte"
    else
      "Payée"
    end
  end
end
Azolo
  • 4,353
  • 1
  • 23
  • 31
Dannoel
  • 161
  • 2
  • 12

1 Answers1

0

Okay... after digging into it, it looks like you cannot do what you want using the find method, according to this post. Sergio usually knows what he is talking about. However one of the other responders, Benjamin, and the answer on this post offer a different approach that should work; using a scope.

So rather than this:

@factures = Facture.find(:all, :conditions => {:facture_statut => 'Ouverte'})

You would need to add a scope to the model and then call the scope:

class Facture < ActiveRecord::Base
  scope :facture_statut lambda {|facture_statut| {:facture_statut => facture_statut}}
  #rest of class
end

And then call it like this:

Fracture.facture_statut('Ouverte')
Community
  • 1
  • 1
ScottJShea
  • 7,041
  • 11
  • 44
  • 67
  • Thanks Scott. I've tried your solution that sounds highly promising and get an error: Unknown key(s): facture_statut Any idea about the problem? – Dannoel Mar 24 '12 at 08:08