0

In Rails 3.2 this worked fine:

class Component < ActiveRecord::Base
  has_and_belongs_to_many :brands
  ...
  scope :branded, ->(b) { includes(:brands).where('brands.id in (?)', b.id) }

Other end of the relationship:

class Brand < ActiveRecord::Base
  has_and_belongs_to_many :components

But I'm upgrading to Rails 4 and it breaks with this message:

Unknown column 'components.brand_ids' in 'where clause'

What's the problem here?

UPDATE

I haven't made the switch to strong parameters yet, and I'm using the protected_attributes gem. Could that be the cause of all this?

t56k
  • 6,769
  • 9
  • 52
  • 115
  • 1
    The error is occurring on that exact line? Why are you performing an `IN` query for a single `id`? Just do `where("brands.id = ?", b.id)` – Damien Roche Aug 13 '14 at 01:54
  • Yeah, not sure why I was doing that. Problem still exists with that line though. – t56k Aug 13 '14 at 02:41
  • Please post your `has_many` and `belongs_to` declaration of your `Component` and `Brand` models. Furthermore check that you run all pending migrations. – spickermann Aug 13 '14 at 03:07
  • can you post the full error stack along with model files ? – Siva Aug 13 '14 at 03:58

1 Answers1

1

Not sure what the branded scope is trying to do, but with the assumption it is to find components that are have a brand X, Component.branded(Brand.find(X))

Maybe try this:

scope :branded, ->(b) { joins(:brands).where(Brand.arel_table[:id].eq b.id)}
tehfailsafe
  • 3,283
  • 3
  • 21
  • 27
  • So this seems to fix it, but I get a similar error for another `has_and_belongs_to_many` relationship. Is this a common Rails 4 issue? – t56k Aug 13 '14 at 04:11
  • Not sure if it's common for everyone, but I do know that after rails 4.0 I converted all my queries to arel_table that would have use a string in the query. https://github.com/camertron/arel-helpers is helpful so you don't have to call `arel_table` every time, you can just use Brand[:id] or Component[:title] etc. – tehfailsafe Aug 13 '14 at 05:46
  • Would love to know why this is necessary, but it's working now. Thanks for your help! – t56k Aug 13 '14 at 06:01