Safe ActiveRecord like query

To ensure that your query string gets properly sanitized, use the array or the hash query syntax to describe your conditions: Foo.where(“bar LIKE ?”, “%#{query}%”) or: Foo.where(“bar LIKE :query”, query: “%#{query}%”) If it is possible that the query might include the % character and you do not want to allow it (this depends on your … Read more

Rails filtering array of objects by attribute value

Try : This is fine : @logos = @attachments.select { |attachment| attachment.file_type == ‘logo’ } @images = @attachments.select { |attachment| attachment.file_type == ‘image’ } but for performance wise you don’t need to iterate @attachments twice : @logos , @images = [], [] @attachments.each do |attachment| @logos << attachment if attachment.file_type == ‘logo’ @images << attachment … Read more

ActiveRecord.find(array_of_ids), preserving order

Oddly, no one has suggested something like this: index = Something.find(array_of_ids).group_by(&:id) array_of_ids.map { |i| index[i].first } As efficient as it gets besides letting SQL backend do it. Edit: To improve on my own answer, you can also do it like this: Something.find(array_of_ids).index_by(&:id).slice(*array_of_ids).values #index_by and #slice are pretty handy additions in ActiveSupport for arrays and hashes … Read more

How does Rails keep track of which migrations have run for a database?

Rails creates a table in your database called schema_migrations to keep track of which migrations have run. The table contains a single column, version. When Rails runs a migration, it takes the leading digits in the migration’s file name and inserts a row for that “version”, indicating it has been run. If you roll back … Read more

Saving multiple objects in a single call in rails

Since you need to perform multiple inserts, database will be hit multiple times. The delay in your case is because each save is done in different DB transactions. You can reduce the latency by enclosing all your operations in one transaction. class Foo belongs_to :parent, :class_name => “Foo” has_many :children, :class_name => “Foo”, :foreign_key=> “parent_id” … Read more

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