Rails Object Relationships and JSON Rendering

By default you’ll only get the JSON that represents modelb in your example above. But, you can tell Rails to include the other related objects as well: def export @export_data = ModelA.find(params[:id]) respond_to do |format| format.html format.json { render :json => @export_data.to_json(:include => :modelb) } end end You can even tell it to exclude certain … Read more

Rails: Order with nulls last

I’m no expert at SQL, but why not just sort by if something is null first then sort by how you wanted to sort it. Photo.order(‘collection_id IS NULL, collection_id DESC’) # Null’s last Photo.order(‘collection_id IS NOT NULL, collection_id DESC’) # Null’s first If you are only using PostgreSQL, you can also do this Photo.order(‘collection_id DESC … Read more

Specifying column name in a “references” migration

For Rails 5+ Initial Definition: If you are defining your Post model table, you can set references, index and foreign_key in one line: t.references :author, index: true, foreign_key: { to_table: :users } Update Existing: If you are adding references to an existing table, you can do this: add_reference :posts, :author, foreign_key: { to_table: :users } … Read more

How can I use ActiveRecord on a database that has a column named ‘valid’? (DangerousAttributeError)

Try this: class MyTable < AR:Base class << self def instance_method_already_implemented?(method_name) return true if method_name == ‘valid’ super end end end It’s a hack, and it might not work in rails 3, but it could fix the problem for now. I found it on the ruby on rails mailing list If you wanted, you could … Read more

Rails gem rails3-jquery-autocomplete: How do I query multiple fields

Your pseudo attribute works only on records already retrieved, but it has no bearing on searching for records. Probably the easiest solution is a named named scope like: scope :search_by_name, lambda { |q| (q ? where([“first_name LIKE ? or last_name LIKE ? or concat(first_name, ‘ ‘, last_name) like ?”, ‘%’+ q + ‘%’, ‘%’+ q … Read more

How do I avoid a race condition in my Rails app?

Optimistic locking is the way to go, but as you might have noticed already, your code will never raise ActiveRecord::StaleObjectError, since child object creation in has_many association skips the locking mechanism. Take a look at the following SQL: UPDATE `scheduled_runs` SET `lock_version` = COALESCE(`lock_version`, 0) + 1, `attendances_count` = COALESCE(`attendances_count`, 0) + 1 WHERE (`id` … Read more

Rails: Overriding ActiveRecord association method

You can use block with has_many to extend your association with methods. See comment “Use a block to extend your associations” here. Overriding existing methods also works, don’t know whether it is a good idea however. has_many :tags, :through => :taggings, :order => :name do def << (value) “overriden” #your code here super value end … Read more