I am trying to find a record based on two associated attributes. The Record should be selected, if its association contains those two records.
So far, I tried following – Which seemed to me a very bad practice and I want to avoid using it.
@size = Spree::OptionValue.find(params[:size])
@color = Spree::OptionValue.find(params[:color])
vari = Spree::Variant.all
vari.each do |va|
if va.option_values.include?(@size && @color)
@variant = va
end
end
So far, I also tried
@variant = Spree::Variant.all(:include => :option_values, :conditions => ['option_value.id = ?', params[:color])
This seems to be the way to go, but I can’t seem to figure out the right way to get the result.
The return error I keep on getting is following:
ActiveRecord::StatementInvalid: PG::Error: ERROR: missing FROM-clause entry for table “option_values”
LINE 1: …_option_values_variants”.”option_value_id” WHERE (option_val…
EDIT:
I got it working due to the great help given in the accepted answer:
Spree::Variant.joins(:option_values).where("spree_option_values.id in (?)", [size, color])
First off, your code is probably broken. I doubt that
.include?(@size && @color)does what you think it does; you’re effectively only checking ifoption_valuesincludes@color. This is equivalent to doing(true && @color). If you want to include both values, you need.include?(@size) && .include?(@color).So your code should probably look like this:
Next, you can make your code much more Ruby-esque:
But it’s far better to actually evaluate the condition at the database level rather than load the entire table into your application. You seem to be looking for all records where the associated
OptionValues includes the two you’ve selected into@sizeand@color.The query you’re looking for probably looks something like this: