Two models:
Invoice
:invoice_num string
:date datetime
.
.
:disclaimer_num integer (foreign key)
Disclaimer
:disclaimer_num integer
:version integer
:body text
For each disclaimer there are multiple versions and will be kept in database. This is how I write the search (simplified):
scope = Invoice.scoped({ :joins => [:disclaimer] })
scope = scope.scoped :conditions => ["Invoice.invoice_num = ?", "#{params[:num]}"]
scope = scope.scoped :conditions => ["Disclaimer.body LIKE ?", "%#{params[:text]}%"]
However, the above search will search again all versions of the disclaimer. How can I limit the search to only the last disclaimer (i.e. the version integer is the maximum).
Please note:
Invoice does not keep the version number. New disclaimers will be added to disclaimer table and keep old versions.
If you want only the invoices with the latest version from disclaimer, put a condition on the
disclaimer_num. And I also suggest creating a helper method inDisclaimerto make the code cleaner in your scope.And I really hope you removed the sql injection prevention code from your scope for brevity.