Search code examples
ruby-on-railsrubyruby-on-rails-3refactoringsqueel

How to use dynamic attributes / columns in Squeel statements?


In my previous issue I ended up that the following code seems to work as expected:

def my_squeel_query
  table_name = Squeel::Nodes::Stub.new("#{self.class.to_s.tableize}_comment_associations".to_sym)

  commenters.
    .where{
      table_name.article_id.eq(my{self.id})
    }
end

Is it possible to make the article_id statement as dynamic as made for the table_name variable?

That is, I would like to make something as-like the following:

def my_squeel_query
  table_name = Squeel::Nodes::Stub.new("#{self.class.to_s.tableize}_comment_associations".to_sym)

  commenters.
    .where{
      table_name.<DYNAMIC_KEY>.eq(my{self.id}) # '<DYNAMIC_KEY>' refers to a column name present in the 'commenters' database table.
    }
end

Solution

  • You can use send.

    column_name = :article_id
    commenters.where{
      table_name.send(column_name).eq(my{self.id})
    }