0

I tried to ask this question previously and it didn't go well - hopefully I do it better this time.

I have three models

class Flavor < ActiveRecord::Base
  has_many :components
  has_many :ingredients, through: :components
end

class Ingredient < ActiveRecord::Base
  has_many :components
  has_many :flavors, through: :components
end

class Component < ActiveRecord::Base
  belongs_to :ingredient
  belongs_to :flavor

  validates :percentage, presence: true 
end

Batches are made of flavors, but a flavor can only be made into a batch if it's components add up to 100 percent (hence why I put the percentage validation in there so it was represented).

At first I tried to write this as a scope, but could never get it to work, the model testing i created worked using

def self.batch_eligible
  self.find_by_sql("Select flavors.* FROM flavors 
  INNER JOIN components on flavors.id = components.flavor_id 
  GROUP BY flavors.id, flavors.name 
  HAVING SUM(percentage)=100")
end

I did make an attempt at the scope and it failed. Here is the final version of the scope I came up with:

scope :batch_eligible, -> {joins(:components).having('SUM(percentage) = 100').group('flavor.id')}

The resultant object will be used to populate a selection list in a form for batches (flavors can exist before the components are fully worked out).

I figure the limitation here is my understanding of scopes - so how would the scope be built properly to produce the same results as the find_by_sql expression?

All help is appreciated, thanks.

In response to the first comment - I tried a variety of scopes without capturing the errors - the scope above returns this error:

 ActiveRecord::StatementInvalid:
   PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "flavor"
   LINE 1: SELECT COUNT(*) AS count_all, flavor.id AS flavor_id FROM "f...
                                         ^
   : SELECT COUNT(*) AS count_all, flavor.id AS flavor_id FROM "flavors" INNER JOIN "components" ON "components"."flavor_id" = "flavors"."id" GROUP BY flavor.id HAVING SUM(percentage) = 100

changing it to flavors id makes it 'work' but it doesn't return the proper information.

One more piece of code - models testing

require 'rails_helper'

RSpec.describe Flavor, type: :model do
  let!(:flavor) {FactoryGirl.create(:flavor)}
  let!(:flavor2) {FactoryGirl.create(:flavor)}
  let!(:ingredient) {FactoryGirl.create(:ingredient)}
  let!(:component) {FactoryGirl.create(:component, flavor: flavor, ingredient: ingredient, percentage: 25)}
  let!(:component1) {FactoryGirl.create(:component, flavor: flavor2, ingredient: ingredient, percentage: 100)}

  it "should have a default archive as false" do
    expect(flavor.archive).to be(false)
  end

  it "should only have valid flavors for batch creation" do
    expect(Flavor.batch_eligible.count).to eq 1
    expect(Flavor.batcH_eligible.first).to eq flavor2
  end
end

Even with a clean test database - the batch_eligible count is 4 - not one

One more note - the tests DO pass with the find_by_sql function being used - I just think a scope should be possible?

7
  • 1
    What errors did you observe when you tried the version you have so far? Have you tried removing parts and seeing what the result are, to see that the pieces work independently? or which piece is the piece that breaks?
    – Taryn East
    Oct 5, 2016 at 2:17
  • 1
    @TarynEast Please see above edit - regarding the error - how i tried to fix it in response to the error and still not working. I really thought this would be an easy thing
    – MageeWorld
    Oct 5, 2016 at 2:26
  • 1
    ok, so re: complaining about the flavour_id thing... you might need to be explicit about what the columns belong to eg maybe try joins(:components).references(:components).having('SUM(components.percentage) = 100').group('components.flavor_id') Also I'd recommend not starting with count -> sometimes a complex scope works but rails has trouble converting it to a proper "count" query... start by making it return .all and then doing a .size on that (just to get it partly-working)... then figure out how to get count working properly.
    – Taryn East
    Oct 5, 2016 at 2:32
  • 1
    Also - instead of testing count... try putsing out the array of flavours, including the sum-percentage and see what you're getting and how it differs from the 1 you expect? Finally, use to_sql to see what it's trying to generate eg: Flavor.batch_eligible.to_sql
    – Taryn East
    Oct 5, 2016 at 2:33
  • 1
    Normally when rails builds a SQl query, it gives each db-table a code-name that is short (eg t3)... but if you're going to use the full table-name in one of the later methods (eg where we use components.flavour_id) then you need to tell rails that you're going to "reference the table name later"... ie references :)
    – Taryn East
    Oct 5, 2016 at 2:54

1 Answer 1

1

Props to @taryneast for the help - I was pointed in the right direction by this.

After correcting the scope issue with flavors.id - I did run the inspect to see what was happening but I also ran a variety of functions.

puts Flavor.batch_eligible.count or puts Flavor.batch_eligible.size both yield the same thing, for example, the hash {312 => 1} - 312 would be the id of the Factory Created Flavor.

So the problem (once I solved flavors.id) wasn't in the scope - it was in the test. You need to test the LENGTH, Flavor.batch_eligible.length yields the integer 1 that I wanted.

Perhaps everyone else knew that - I didn't.

Thank you Taryn

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.