problem about arel-Collection of common programming errors


  • crispy
    ruby-on-rails activerecord arel scopes
    I have encountered some unexpected behavior in Active Record (3.2.13):There is a simple scope on my model:class User < ActiveRecord::Basescope :verified, lambda { where(‘verified = 1’) } endThis can be used fine on its own:User.verified.to_sql#=> “SELECT \”users\”.* FROM \”users\” WHERE (verified = 1)”When I concatenate where-clauses, they are anded as expected:User.where(company_id: 1).where(company_id: 2).to_sql”SELECT \”users\”.* FROM \”users\” WHERE \”users\”.\”company_id\” = 1 AND \

  • finpingvin
    sql ruby-on-rails ruby ruby-on-rails-3 arel
    I have trouble with using Arel to aggregate 2 columns in the same query. When I run this, the whole server freezes for a minute, before the rails dev-server crashes. I suspect an infinite loop :). Maybe I have misunderstood the whole concept of Arel, and I would be grateful if anybody could have a look at it.The expected result of this query is something like this: [{:user_id => 1, :sum_account_charges => 300, :sum_paid_debts => 1000},…]a_account_charges = Table(:account_charges) a_paid_debts

  • Jack Juiceson
    sql ruby-on-rails activerecord arel squeel
    tl;drHow to convert below SQL to Arel(or whatever is considered standard in Rails)@toplist = ActiveRecord::Base.connection.execute(‘select ci.crash_info_id,count(distinct(user_guid))[Occurences], c.md5 from crashes ci join crash_infos c on c.id=crash_info_id group by ci.crash_info_idorder by [Occurences] desc’)— end of tl;dr —-I’m working on a small web project, it’s goal is to take our customers crash reports(when our desktop app crashes, we send diagnostics to our servers), analyze them an

  • stephan.com
    sql ruby-on-rails-3 arel
    I’m desperately trying to make sense of Arel, mostly because I hate dealing with SQL; I was doing so well, but I’ve hit a wall.I’ve been working in Rails 3.0.0, and I’m trying to make a complex query with some math in it. The real case is rather more complex, but I’ve simplified a bit. In my example, I have a table with a particular string field, and I want a count of all the records, as well as a count for each of two possible values of that field, grouped by a foreign id.Under Rails 3.0.0, I

  • neezer
    sql ruby-on-rails-3 postgresql activerecord arel
    UPDATE: So thanks to @Erwin Brandstetter, I now have this:def self.unique_users_by_company(company)users = User.arel_tablecards = Card.arel_tableusers_columns = User.column_names.map { |col| users[col.to_sym] }cards_condition = cards[:company_id].eq(company.id).and(cards[:user_id].eq(users[:id]))User.joins(:cards).where(cards_condition).group(users_columns).order(‘min(cards.created_at)’) end… which seems to do exactly what I want. There are two shortcomings that I would still like to have addr

  • Adam Lassek
    ruby-on-rails ruby-on-rails-3 join multiple-databases arel
    I’m trying to move my User account and session data into a separate database so that we can eventually share it across multiple applications.I’ve seen plenty of people online saying to use establish_connection to tell a model to connect to a different db, but I am unable to get this to work.config/database.ymldevelopment:adapter: mysql2encoding: utf8reconnect: truepool: 5host: localhostdatabase: project_name_developmentauthentication:adapter: mysql2encoding: utf8reconnect: truepool: 5host: local

  • Kevin Sylvestre
    ruby-on-rails ruby activerecord arel
    I have the following example query:source = “(SELECT DISTINCT source.* FROM (SELECT * FROM items) AS source) AS items” items = Item.select(“items.*”).from(source).includes([:images]) p items # [#<Item id: 1>, #<Item id:2>]However running:p items.count Results in NoMethodError: undefined methodmap’ for Arel::Nodes::SqlLiteral`I appreciate the query is silly, however the non-simplifieid query is a bit too complicated to copy and this was the smallest crashing version I could create. An

  • David Tuite
    ruby-on-rails ruby-on-rails-3 activerecord geocoding arel
    I have a bus model and an event model. Each bus is going to an event:class Bus < ActiveRecord::Basebelongs_to :eventbelongs_to :origin endclass Event < ActiveRecord::Basehas_many :buses endAs you can see, each bus also has an origin (the place it leaves from). An origin can have many buses leaving from it. Origins are geocoded (by the [Geocoder gem][1]) on creation so that they have a latitude and longitude associated with them.class Origin < ActiveRecord::Basehas_many :busesgeocoded_by

  • Dmytrii Nagirniak
    sql ruby-on-rails ruby activerecord arel
    How can you combine 2 different conditions using logical OR instead of AND?NOTE: 2 conditions are generated as rails scopes and can’t be easily changed into something like where(“x or y”) directly.Simple example:admins = User.where(:kind => :admin) authors = User.where(:kind => :author)It’s easy to apply AND condition (which for this particular case is meaningless):(admins.merge authors).to_sql #=> select … from … where kind = ‘admin’ AND kind = ‘author’But how can you produce the f

  • Elliot
    sql ruby-on-rails subquery arel
    I am trying to build this query in ARel:SELECT FLOOR(AVG(num)) FROM ( SELECT COUNT(attendees.id) AS num, meetings.club_id FROM `meetings` INNER JOIN `attendees` ON `attendees`.`meeting_id` = `meetings`.`id` WHERE (`meetings`.club_id = 1) GROUP BY meetings.id) tmp GROUP BY tmp.club_idIt returns the average number of attendees per meeting, per club. (a club has many meetings and a meeting has many attendees)So far I have (declared in class Club < ActiveRecord::Base):num_attendees = meetings.sel

  • number5
    ruby-on-rails-3 postgresql-9.1 arel sequel hstore
    I would like to use the Squeel gem (based on Arel) for my Rails app (v 3.2.6). My hstore column is called properties.These work perfectly fine:User.where{(firstname == ‘Ryan’) & (lastname == ‘Bates’)} User.where{“properties @> (‘male’ => ‘1’)”}The second example is a plain Postgres query, because Squeel doesn’t seem to support hstore functions.These don’t work:User.where{“properties @> (‘male’ => ‘1’)” & firstname == ‘Ryan’} User.where{(“properties @> (‘male’ => ‘1’)”)

  • Gilles
    ruby-on-rails postgresql arel
    I’ve got some SQL that’s working when I want to look for particular pages that have the particular schemes assigned to it (all through the scheme_assignment):Page.find_by_sql(“SELECT pages.idFROM pagesINNER JOIN scheme_assignments ON (scheme_assignments.schemable_type = ‘Page’ ANDscheme_assignments.schemable_id = pages.sid)INNER JOIN schemes ON (schemes.sid = scheme_assignments.scheme_id ANDschemes.sid IN (4,6,7))GROUP BY pages.id”)When I tried to convert this to ARel:Page.select(“pages.id”).joi

  • Dylan Markow
    ruby ruby-on-rails-3 activerecord arel
    I’m getting to grips with Rails 3 and I can’t seem to do a basic find from a result set. My code looks like the following:@project = @user.where({:projects => {:project_member_id => user.id}}).find_by_id(params[:id])I understand that the “where” section will not return a collection but merely create a query that is waiting to be run against the db. However, I can’t understand why I get the following error when I try to run the find_by_id:undefined method `to_sql’ for #<Arel::Attributes:

  • Pierre Schambacher
    sql ruby-on-rails-3 activerecord ruby-on-rails-3.2 arel
    I have a few massive SQL request involving join across various models in my rails application. A single request can involve 6 to 10 tables.To run the request faster I want to use sub-queries in the joins (that way I can filter these tables before the join and reduce the columns to the ones I need). I’m trying to achieve this using ARel.I thought I found the solution to my problem there: How to do joins on subqueries in AREL within Rails But things must have changed because I get undefined method

  • Chris Travers
    ruby-on-rails-3 arel ransack
    I am using Ransack in my Rails 3.2.11 app and love it. I’m currently searching Profiles that match a given high school like so:<%= f.check_box :profile_high_school_cont, {}, “#{current_user.profile.high_school}”, ” %>However I’d like to add some additional logic to this and further refine the search to Profiles that allow other users to find them by their high school.So I’m wondering if there is a way to add a check for whether a Profile’s :show_high_school is true in addition to whether

  • fl00r
    ruby ruby-on-rails-3 activerecord arel
    Whenever i tried to useTable.create :a=>”a”, :b=>”b”ortab=Table.new tab.a=”a” tab.b=”b” tab.save!produces NoMethodError: undefined method `name’ for nil:NilClass my table model is class Table < ActiveRecord::Base set_table_name “table”set_primary_key “id” end

  • Chris Keele
    ruby-on-rails ruby activerecord arel squeel
    The questionI’m trying to wrap my head around arel and squeel, but I feel like I lack the vocabulary to ask Google what I’m looking for.TL;DR: Does anyone know how to mimic Squeel’s Model.where{related.objects.field.matches string} syntax out of composed Squeel::Node objects?The problemThis question demonstrates how to build a Squeel KeyPath from a string, like so:search_relation = ‘person.pets’ User.joins{Squeel::Nodes::KeyPath.new(search_relation.split(‘.’))} # Mimics User.joins{person.pets}Th

  • amd
    sql ruby-on-rails-3 activerecord arel
    I have an app that has a number of Post models, each of which belongs_to a User model. When these posts are published, a PublishedPost model is created that belongs_to the relevant Post model.I’m trying to build an ActiveRecord query to find published posts that match a user name, then get the ids of those published posts, but I’m getting an error when I try to use the pluck method after eager-loading my associations and searching them with the where method. Here’s (part of) my controller:class

  • Alan McCann
    ruby-on-rails ruby arel
    I was implementing my first HABTM relationship and have run into an issue with my query. I am looking to validate my approach and to see if I have found a bug in the AREL (or some other part of Rails) code.I have the following modelsclass Item < ActiveRecord::Basebelongs_to :userbelongs_to :categoryhas_and_belongs_to_many :regions endclass Region < ActiveRecord::Basehas_ancestryhas_and_belongs_to_many :items endI have the associated items_regions table:class CreateItemsRegionsTable < Ac

Web site is in building