开发者

How do I able to create a user before initialization of model

In my model(Product) i have a validation, that each product should have a valid owner (login_id of user)

validates_presence_of :owner
validates_inclusion_of :owner, :in => User.first.login_id, :message => "%{value} is not a valid owner name"

I am trying to create product mock object using factory girl

for creating a new product I need login_id of a user. to do so i have create a user.

up to this every thing is ok, but when i am trying to create a Product using that user's login_id product is not create, and displaying validation message ("User1 is not a valid owner name").

After digging into deeper i found tha开发者_开发技巧t

  1. Problem arise from validation in my model.
  2. I have a validation (validates_inclusion_of :owner, :in => User.first.login_id) which initialize before creating the mock user in factory.rb, (up to that time no user is created in database, user is created after initialization of model when it execute factory.rd )

My question is: 1. How do I able to create a user before initialization of model.


Can you not create a user object, and then pass that object to your product factory? This should create a valid user and then supply it through the owner association and make the product valid.

user = Factory(:user, :name => "User1")
product = Factory(:product, :owner => user)

This user apparently has to be the first user too? So if you have existing user objects then you can try clearing all users before you create the first one.

User.delete_all


I solve this problem as follows:

In my model I have replaced the 'Rails validation' by writing Custom validation method. This custom validation method will be called at the time of creating 'Product'.

validates_presence_of :owner
validate :owner_should_be_registered_user

def owner_should_be_registered_user
    if !User.all_user.include? owner and !owner.nil?
      errors.add(:owner, "is not a valid user")
    end
  end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜