undefined method `joins' for #<Arel::SelectManager>

4.1k views Asked by At

I'm trying to convert this query from raw SQL to Arel (6.0.0), but I'm running into problems that I never had before Arel was rebuilt from the ground up in later versions. The error I'm getting, specifically, is:

undefined method `joins' for #<Arel::SelectManager>

This error occurs are starting an ActiveRecord joins query, and then appending another joins. Any idea how I should combine joins with ActiveRecord (and Arel predicates?)

The new code:

v = o.joins(Vote.table_name).on(Vote.arel_table[:voteable_type].eq(o.to_s).and(Vote.arel_table[:voteable_id].eq(o.arel_table[o.primary_key])))
        v = v.joins(self.class.base_class.table_name).on(self.base_class.arel_table[self.class.base_class.primary_key].eq(o.arel_table[p[0]]))
        v = v.where(self.class.base_class.areal_table[self.class.base_class.primary_key].eq(self.id))

converted from:

v = o.where(["#{self.class.base_class.table_name}.#{self.class.base_class.primary_key} = ?", self.id])
v = v.joins("INNER JOIN #{Vote.table_name} ON #{Vote.table_name}.voteable_type = '#{o.to_s}' AND #{Vote.table_name}.voteable_id = #{o.table_name}.#{o.primary_key}")
v = v.joins("INNER JOIN #{self.class.base_class.table_name} ON #{self.class.base_class.table_name}.#{self.class.base_class.primary_key} = #{o.table_name}.#{p[0]}")

o is an ActionModel Instance. If anyone's interested, this if for use in the thumbs_up gem.

Any help would be appreciated!

2

There are 2 answers

0
coorasse On BEST ANSWER

Is join in Arel not joins

vote_t = Vote.arel_table    
other_t = self.class.base_class.arel_table
v = o.join(vote_t).on(vote_t[:voteable_type].eq(o.to_s).and(vote_t[:voteable_id].eq(o.arel_table[o.primary_key])))
v = v.join(other_t).on(other_t[self.class.base_class.primary_key].eq(o.arel_table[p[0]]))
v = v.where(other_t[self.class.base_class.primary_key].eq(self.id))
1
Gavin Miller On
v = o.joins(Vote.table_name).on(Vote.arel_table[:voteable_type].eq(o.to_s).and(Vote.arel_table[:voteable_id].eq(o.arel_table[o.primary_key])))

From the looks of it, your first line starts with o which I'm guessing is some type of ActiveRecord model. ActiveRecord defines the joins method as you already know.

However the output from the first line is not another ActiveRecord model, but instead an instance of Arel::SelectManager. The problem then, is that joins is not defined for that instance, instead you want the join method.

Anything more than that is difficult to suss out since your code is lacking in details (if you could provide more details I can potentially expand on my answer.)

<opinion> If I were to stumble upon either piece of code, I'd likely try to write it out in raw SQL, since both examples are difficult to understand </opinion>