I have 3 tables & models:
brands
brand_data_records
and
brand_data_records_brands – the join table
In rails i want all brand_data_records for a given date range for a given brand where a given attribute is not null in the db.
So I have:
BrandDataRecord.find(:all, :select => column_match, :joins => :brands, :conditions => ["brand_data_records_brands.brand_id = ? and date_retrieved >= ? AND date_retrieved <= ? and ? IS NOT NULL",brand.id,start_date,end_date,column_match])
This generates this sql:
SELECT sentiment FROM `brand_data_records` INNER JOIN `brand_data_records_brands` ON `brand_data_records_brands`.brand_data_record_id = `brand_data_records`.id INNER JOIN `brands` ON `brands`.id = `brand_data_records_brands`.brand_id WHERE (brand_data_records_brands.brand_id = 330516084 and date_retrieved >= '2011-05-02' AND date_retrieved <= '2011-06-01' and 'sentiment' IS NOT NULL)
Which generally works, but it gives back a bunch of extra records that have a null value. I think its something to do with the joins, if I remove them with sql only it works fine, but im not sure how to fix in rails (or even in sql for that fact)
You probably mean to reference the column:
What you’re doing inadvertently is asserting that the string
'sentiment'is not null, which of course it will never be. Passing in:sentimentor'sentiment'.to_sym'in your conditions should fix this as symbols get escaped with backquotes on conversion.