Rails model.valid? flushing custom errors and falsely returning true

In ActiveModel, valid? is defined as following: def valid?(context = nil) current_context, self.validation_context = validation_context, context errors.clear run_validations! ensure self.validation_context = current_context end So existing errors are cleared is expected. You have to put all your custom validations into some validate callbacks. Like this: validate :check_status def check_status errors.add(:status, “must be YES or NO”) unless … Read more

Rails 3 – select with Include?

There is a select method in ARel, but you must use the correct table names (i.e. plural and beware if you have polymorphic models or if you’re using set_table_name or some other similar non-standard practice) @items = Item. select(‘users.name’, ‘users.created_at’, ‘orders.created_at’, ‘suppliers.name’, ‘agents.name’, ‘manufacturers.name’). where(:users => { :fulfilled => true }). includes(:orders => [:supplier, :agent], … Read more

How would you test observers with rSpec in a Ruby on Rails application?

You are on the right track, but I have run into a number of frustrating unexpected message errors when using rSpec, observers, and mock objects. When I am spec testing my model, I don’t want to have to handle observer behavior in my message expectations. In your example, there isn’t a really good way to … 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

Creating or updating a has_one ActiveRecord association

if property.contract.nil? property.create_contract(some_attributes) else property.contract.update_attributes(some_attributes) end Should do the trick. When you have a has_one or belongs_to association then you get build_foo and create_foo methods (which are like Foo.new and Foo.create). If the association already exists then property.contract is basically just a normal active record object.

Validating a Model Property is Greater than Another

As you noticed, the only way is to use a custom validator. The :greater_than option should be an integer. The following code won’t work because both current and next release are available only at instance-level. class Project < ActiveRecord::Base validates_numericality_of :current_release validates_numericality_of :next_release, :greater_than => :current_release end The purpose of the greater_than option is to … Read more

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