Rails 3 / Ruby: ActiveRecord Find method IN condition Array to Parameters single quote issue

Answer updated (twice) to reflect Rails 3+ ActiveRecord syntax Rails 3+ You can use the following syntax: Post.where(user_id: [1,2,3]) And thus: Post.where(user_id: args) Rails 3 or Rails 4 (Original) For completeness, the Rails 3 syntax would be: Post.where(“user_id IN (?)”, [1,2,3]).to_a If args is an Array, then: Post.where(“user_id IN (?)”, args).to_a Or, if args is … Read more

Query records through its belongs_to relation in Rails

With the latest rails versions you can do: Activity.joins(:location).where(locations: { country: “Australia” }) Beware: it is location (singular) in joins(:location) because it references the belongs_to relationship name it is locations (plural) in where(…) because it references the table name The latter means that if you had the following: belongs_to :location, class_name: “PublicLocation” the query would … Read more

Is it a good idea to purge old Rails migration files?

The Rails 4 Way page 177: Sebastian says… A little-known fact is that you can remove old migration files (while still keeping newer ones) to keep the db/migrate folder to a manageable size. You can move the older migrations to a db/archived_migrations folder or something like that. Once you do trim the size of your … Read more

Rails PG::UndefinedTable: ERROR: missing FROM-clause entry for table

The error ERROR: missing FROM-clause entry for table “agency” …should hint that somewhere in your query you have mistakenly used agency as a table name, without pluralizing it. But where exactly did you do that? The only difference between working and non-working snippets of yours are these bits: joins(:agency). where(agency: {state: ‘active’}). …a-and both lines … Read more

ActiveRecord appends ‘AND (1=0)’ to end of queries

Rails will generate SQL like AND (1=0) when you query for a column whose value is in an empty array: Child.where(id: []) Intuitively, you’d expect that to generate SQL like SELECT * FROM children WHERE id IN (), but () isn’t actually valid SQL. Since no rows will match that query, though, Rails works around … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)