views:

32

answers:

2

Hello!

I have model:

class Company < ActiveRecord::Base
  attr_accessible :name, :address, :description, :email, :www   
  validates_presence_of :name, :address, :email
  validates_uniqueness_of :user, :name, :email
  validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
  has_many :items, :dependent => :destroy
  has_one :user  
end

And test-case:

class CompanyTest < ActiveSupport::TestCase
  should_allow_mass_assignment_of :name, :address, :description, :email, :www
  should_have_one :user
  should_have_many :items, :dependent => :destroy
  should_validate_uniqueness_of :name, :email  #failed
  should_validate_presence_of :name, :address, :email  #failed
  should_not_allow_values_for :email, "not valid email"  #failed
  should_allow_values_for :email, "[email protected]"  #failed
end

Some generated tests fails with strange error:

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: companies.user: SELECT "companies".id FROM "companies" WHERE ("companies"."user" IS NULL)  LIMIT 1

I cannot understand why it tried to access "user" column of company table. It's not exists, because User model contains "belongs_to :company" and column "company_id"

A: 

Afaik has_one expects the source table to define the relation_id column. In your case I assume the companies table stores the user_id column. So you have alter the has_one definition to specifiy the direction and foreign key, or change it to a belongs_to.

Tanel Suurhans
A: 

Incorrect validation:

validates_uniqueness_of :user

without this line, everything ok!

alexandr