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

Rails: How to reference images in CSS within Rails 4

Sprockets together with Sass has some nifty helpers you can use to get the job done. Sprockets will only process these helpers if your stylesheet file extensions are either .css.scss or .css.sass. Image specific helper: background-image: image-url(“logo.png”) Agnostic helper: background-image: asset-url(“logo.png”, image) background-image: asset-url($asset, $asset-type) Or if you want to embed the image data in … Read more