Rails: validate uniqueness of two columns (together)

You can use a uniqueness validation with the scope option. Also, you should add a unique index to the DB to prevent new records from passing the validations when checked at the same time before being written: class AddUniqueIndexToReleases < ActiveRecord::Migration def change add_index :releases, [:country, :medium], unique: true end end class Release < ActiveRecord::Base … Read more

How do you manually execute SQL commands in Ruby On Rails using NuoDB

The working command I’m using to execute custom SQL statements is: results = ActiveRecord::Base.connection.execute(“foo”) with “foo” being the sql statement( i.e. “SELECT * FROM table”). This command will return a set of values as a hash and put them into the results variable. So on my rails application_controller.rb I added this: def execute_statement(sql) results = … Read more

Rails: How do I create a default value for attributes in Rails activerecord’s model? [duplicate]

You can set a default option for the column in the migration …. add_column :status, :string, :default => “P” …. OR You can use a callback, before_save class Task < ActiveRecord::Base before_save :default_values def default_values self.status ||=”P” # note self.status=”P” if self.status.nil? might better for boolean fields (per @frontendbeauty) end end

Rails find_or_create_by more than one attribute?

Multiple attributes can be connected with an and: GroupMember.find_or_create_by_member_id_and_group_id(4, 7) (use find_or_initialize_by if you don’t want to save the record right away) Edit: The above method is deprecated in Rails 4. The new way to do it will be: GroupMember.where(:member_id => 4, :group_id => 7).first_or_create and GroupMember.where(:member_id => 4, :group_id => 7).first_or_initialize Edit 2: Not … Read more

What is causing this ActiveRecord::ReadOnlyRecord error?

Rails 2.3.3 and lower From the ActiveRecord CHANGELOG(v1.12.0, October 16th, 2005): Introduce read-only records. If you call object.readonly! then it will mark the object as read-only and raise ReadOnlyRecord if you call object.save. object.readonly? reports whether the object is read-only. Passing :readonly => true to any finder method will mark returned records as read-only. The … Read more

delete_all vs destroy_all?

You are right. If you want to delete the User and all associated objects -> destroy_all However, if you just want to delete the User without suppressing all associated objects -> delete_all According to this post : Rails :dependent => :destroy VS :dependent => :delete_all destroy / destroy_all: The associated objects are destroyed alongside this … Read more

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