vendredi 27 mars 2015

validate_presence_of on 'has_many' and 'belongs_to' association, how to write factory

I have a two models. Both having validate_presence_of .



class Company < ActiveRecord::Base
has_many :projects
validate_presence_of :projects

def save_projects(projects)
projects.each do |project|
project.company = self
project.save(:validate => false)
end
end
end


In method saving_projects(projects) is called before saving company in controller. Means I am saving company after the project.



class Project < ActiveRecord::Base
belongs_to :company
validate_presence_of :company
end


These are my models.


I am saving projects in model with validation => false. So I want to write factory for company.


What I have tried:



factory :company do
name 'Test'
user
before_create do |company|
FactoryGirl.build(:project, :company => company)
end
end


And also tried this



factory :company do
name 'Test'
user
after_build do |company|
company.projects << FactoryGirl.build(:project, :company => company)
end
end


I am getting this error:



Failure/Error: company = FactoryGirl.build(:company, :user=>user,:name => "test")
NoMethodError:
undefined method `company=' for #<Project:0x000000106c3030>


Problem track: The problem with validate_presence_of on both the model that causing issue.


Aucun commentaire:

Enregistrer un commentaire